It is a very basic question, but I don't seem to understand why this doesn't work. As far as I know, a
and b
would be pointers (in C thinking) to Integer objects. Why is the output 3 2
and not 3 3
? I would have expected the value of b to also be incremented when incrementing a.
Integer a = new Integer(1);
Integer b = new Integer(2);
a = b;
a++;
System.out.print(a + " " + b);
Firstly, in case of java, the term used is an object 'reference' and not a 'pointer'. Basically it means that its a logical reference to the actual object.
Further more as already noted by Lagerbaer, its autoboxing-unboxing that is transparent which effectively increments the value, creates a new object and then assigns it back to the reference.
So at the end of the increment operation, there are two objects instead of one.
The increment operation after unboxing would probably look something like this :
a = Integer.valueOf(a.intValue()++);
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