Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying one object to another Object is yielding different results in java

Tags:

java

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.

like image 964
Abhishek Avatar asked Mar 03 '15 06:03

Abhishek


People also ask

What happens when you assign an object to another object in Java?

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.

What happens when one object is assigned to another object?

Explanation: When one object reference variable is assigned to another object reference variable then a copy of the reference is created.

What happens when an object is assigned to another object reference of the same class?

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.


1 Answers

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

like image 133
muasif80 Avatar answered Oct 13 '22 13:10

muasif80