public static void main(String[] args) {
Integer a = 1;
Integer b = 0;
b=a;
System.out.println(a);
System.out.println(b);
++a;
System.out.println(a);
System.out.println(b);
}
output : 1 1 2 1
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(1);
a.add(1);
a.add(1);
b=a;
System.out.println(a.size());
System.out.println(b.size());
b.add(2);
System.out.println(a.size());
System.out.println(b.size());
}
output : 4 4 5 5
For above code why both objects are not referring to same memory location.
what happens when you assign one object to another object ?? It assigns the reference of the Object. In other words, both variables 'point' to the same Object. For example/ int [] a = new int[5]; int [] b = a; b and a now 'point' to the same array.
Explanation: When one object reference variable is assigned to another object reference variable then a copy of the reference is created.
If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.
All the wrapper classes are immutable in Java actually. We know String as a famous immutable class. In addition to it other wrappers like Integer is also immutable.
See this http://www.javaworld.com/article/2077343/learn-java/java-s-primitive-wrappers-are-written-in-stone.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With