K.Steff K.Steff - 6 months ago 39
Java Question

Is Integer Immutable

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

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 == "hello"
str = str + "world";
// now str == "helloworld"

So what happened there? Since String is immutable, clearly str was not changed. But it now equals something different. This is because str is now a completely newly instantiated object, just as your Integer is. So the value of a did not mutate, per se, but it was replaced with a completely new object, i.e. new Integer(6).