Check this snippet :
Integer i = 42; Integer j = i; // copy reference ++j; // increment value System.out.println("" + i + j); // print 4243 System.out.println(i == j); // print false
This code uses reference, then why both references don’t increase simultaneously, and why references are not equals ?
Remember that operator overloading doesn’t exist in Java. Thus here, ++ operator cannot act on j with j considered as a reference. Indeed increment operator can be applied only on primitive types, but here j is reference and this code compile and run fine.
In fact, when you increase a value with ++ operator on Integer, javac use boxing and unboxing.
Here, to use ++ operator on Integer, javac unbox the int value from reference, increase it, and rebox it into a new reference (the old will be lost and cleared by the garbage collector).
Because j is a different reference, equality fails, and values are different (only j has the new value).
For best understanding, check this code, it look like the real behavior of increment operator on Integer reference :
Integer i = 42; Integer j = i; int _j = j; ++_j; j = Integer.valueOf(_j); System.out.println("" + i + j); System.out.println(i == j);
This version of the code is simplified, but if you compile the first snippet, and uncompile it (with jad), you’ll get :
Integer i = Integer.valueOf(42); Integer j = i; j = Integer.valueOf(j.intValue() + 1);
This behaviour is very rarely annoying, but it’s fun to know that.