Suppose we do:
Integer i = 3; Integer j = i; i++; System.out.println("i = " + i + ", j = " + j);
What values are printed?
Since Integer is an immutable reference type, it is stored in a box containing a value that is unchanged after the box has been created.
The variables i and j do not contain the numeric values, but contain pointers to boxes that contain the values. Initially, i and j point to the same box, containing 3.
What can Java do in response to i++? It cannot change the 3 value inside the box, since it is immutable. Instead, Java must find or make a new box containing the value 4. After the statement i++, i points to this new box, while j still points to the old box containing 3.
Java caches boxes for small integers so that it does not have to make a new box every time.
Prev Next Page+10