Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the value updated?

Tags:

java

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);
like image 420
Toma Radu-Petrescu Avatar asked Jan 19 '17 20:01

Toma Radu-Petrescu


1 Answers

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()++);
like image 105
Ravindra HV Avatar answered Oct 11 '22 06:10

Ravindra HV