An Integer is immutable (its value cannot be changed).

Suppose we do:

Integer i = 3;
Integer j = i;
System.out.println("i = " + i + ", j = " + j);

What values are printed?

  • A: i = 4, j = 4
  • B: i = 4, j = 3
  • C: i = 3, j = 4
  • D: i = 3, j = 3
  • E: error

    Answer: B

    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