K.Steff K.Steff - 2 years ago 183
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;

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download