An Integer
in Java is immutable. You can not change its value. In addition, it's a special autoboxing type to provide an Object wrapper for the int
primitive.
In your code, for example, x++
does not modify the Integer
object x
is referencing. It un-autoboxes it to a primitive int
, post-increments it, re-autoboxes it returning a new Integer
object and assigns that Integer
to x
.
Edit to add for completeness: Autoboxing is one of those special things in Java that can cause confusion. There's even more going on behind the scenes when talking about memory / objects. The Integer
type also implements the flyweight pattern when autoboxing. Values from -128 to 127 are cached. You should always use the .equals()
method when comparing Integer
objects.
Integer x = 5;
Integer y = 5;
if (x == y) // == compares the *reference (pointer) value* not the contained int value
{
System.out.println("They point to the same object");
}
x = 500;
y = 500;
if (x != y)
{
System.out.println("They don't point to the same object");
if (x.equals(y)) // Compares the contained int value
{
System.out.println("But they have the same value!");
}
}
See: Why aren't Integers cached in Java? for more info (and of course the JLS)