Is Integer Immutable
Immutable does not mean that a
can never equal another value. For example, String
is immutable too, but I can still do this:
String str = "hello";
// str equals "hello"
str = str + "world";
// now str equals "helloworld"
str
was not changed, rather str
is now a completely newly instantiated object, just as your Integer
is. So the value of a
did not mutate, but it was replaced with a completely new object, i.e. new Integer(6)
.
You can determine that the object has changed using System.identityHashCode()
(A better way is to use plain ==
however its not as obvious that the reference rather than the value has changed)
Integer a = 3;
System.out.println("before a +=3; a="+a+" id="+Integer.toHexString(System.identityHashCode(a)));
a += 3;
System.out.println("after a +=3; a="+a+" id="+Integer.toHexString(System.identityHashCode(a)));
prints
before a +=3; a=3 id=70f9f9d8
after a +=3; a=6 id=2b820dda
You can see the underlying "id" of the object a
refers to has changed.
a
is a "reference" to some Integer(3), your shorthand a+=b
really means do this:
a = new Integer(3 + 3)
So no, Integers are not mutable, but the variables that point to them are*.
*It's possible to have immutable variables, these are denoted by the keyword final
, which means that the reference may not change.
final Integer a = 3;
final Integer b = 3;
a += b; // compile error, the variable `a` is immutable, too.