Java – Immutable String and Integer in Java: What is the point if assignment in effect changes the value

immutabilityjava

If immutability is "good" and yet you can in effect change the value in an Integer or String variable (never mind that you get a new reference — the value has changed) what good is it that Integer and String are immutable?

If Integer were mutable, what sort of bugs would be harder to find (etc.) than in the case that Integer is immutable? Or with String?

Best Answer

never mind that you get a new reference

No! Do mind that fact - it is the key in understanding the point of immutable objects.

-- the value has changed

No, it hasn't. You have a different object with a different value in this place in the code.

But any other part of the code which had a reference to the original object still has that reference to that object with the original value.

Immutability is good because it prevents you from making a change to an object and having that change affect a completely different part of the code which wasn't written with the possibility in mind that the objects it operates on could be changed somewhere else (very little code is really written to cope with that).

This is particularly useful with multithreaded code (where a change done by a different thread could happen in between the operations of a single line of code), but even single-threaded code is much easier to understand when methods you call can't change the objects you pass into them.