Is Integer Immutable

K.Steff picture K.Steff · Apr 6, 2011 · Viewed 68.6k times · Source

I know this is probably very stupid, but a lot of places claim that the Integer class in Java is immutable, yet the following code:

Integer a=3;
Integer b=3;
a+=b;
System.out.println(a);

Executes without any trouble giving the (expected) result 6. So effectively the value of a has changed. Doesn't that mean Integer is mutable? Secondary question and a little offtopic: "Immutable classes do not need copy constructors". Anyone care to explain why?

Answer

Travis Webb picture Travis Webb · Apr 6, 2011

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).