progyammer
progyammer

Reputation: 1508

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??

Upvotes: 0

Views: 173

Answers (2)

Ralf Kleberhoff
Ralf Kleberhoff

Reputation: 7290

For an Integer x, the expression x++ can be understood like x = new Integer(x.intValue() + 1);. Its not exactly the same, but helps for understanding.

So, it doesn't modify the Integer object with the value 10 that x pointed to before the x++, it creates a new Integer object with the value 11 independent of the original 10 Integer, and assigns this 11 Integer to x.

But there's nothing in the x++ expression that would make y point to a different Integer instance. So y still points to the original 10.

That's the difference to the CLA example where you don't introduce a new instance with ob1.val++, but modify the single instance. If the Integer class had a public field value, then x.value++ would show the behaviour you expected - but the value field is (for good reason) private - not accessible to the outside.

Upvotes: 1

Matt
Matt

Reputation: 3662

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.

Upvotes: 1

Related Questions