Search code examples
javawrapperautoboxing

Do wrapper class objects get unboxed while being assigned to another object?


When we assign objects of the same type to one another, the new object stores the address of the object that's being assigned to it. For instance, if I have my own class named CLA then the following code will produce 11 as the output:

public class CLA{
    int val;
    public static void main(String...args){
        CLA ob1 = new CLA();
        ob1.val = 10;
        CLA ob2 = ob1;
        ob1.val++;
        System.out.printf("%d", ob2.val);
    }
}

because ob2 would refer to ob1 and consequently show ob1's val.

However, the same doesn't happen for Wrapper classes. When I assign an Integer object to another, the operation simply behaves like we're dealing with values and not objects. As opposed to the above code, the output of the below code is 10:

Integer x = 10; //auto-boxed as new Integer(10)
Integer y = x;
x++;
System.out.printf("%d", y.intValue());


Why does this happen?

Do wrapper class objects get unboxed while being assigned to another object, so as to pass the value instead of the address??


Solution

  • When you do x++, it is the same as x = x + 1 so it is actually a new instance of Integer assigned to x but y still points to the old instance which value is 10.

    Keep in mind that wrapper instances are immutable.