Why are Integers immutable in Java?
You won't find a mandatory reason why java.lang
wrappers must be immutable. Simply because it's a design decision. They could have decided otherwise. The language designers had to choose between mutable and immutable. And they chose immutable. That's it.
There are some compelling (IMO) reasons though to make them immutable:
It's consistent with String
. The same reasoning you provided for String
to be immutable applies to Integer
etc. as well (e.g. think of a port number in a property map). This generally applies to any mutable type.
Immutable types rule out a plethora of hard to find mistakes one can make where one involuntarily changed an objects member value by modifying the value obtained through a getter. It saves a lot of defensive copying when the type is immutable. The most infamous example is java.util.Date
, which is generally a pain to use because it's mutable (API issues aside).
Also immutable types allow for the use of shared instances, like e.g. Integer
does for commonly used values (see Integer.valueOf(int)
).
Can the identity of the value 1
ever change? Can it become 2
? No. That's why Integer
and other numeric types are immutable. They're meant to model that identity.
An integer literal (2, 3) is also immutable e.g. int var=3;
It's the int
variable (var
on the left had side) that is mutable. The intention of Integer is "object as a value" (right hand side) rather than "object as a variable" (left hand side). Since Java uses references, variability (mutability) can be either in reference or in the object contents. The object reference (variable r
in Integer r=2;
) can be the variable aspect of this situation. As a result, variability is provided via a "variable reference" rather than "constant reference (i.e. no reference) to a variable primitive-typ content". It would be using a constant reference (constant r
) and a variable content of the referred object.
They could have designed the class name Integer
as a variable (non-immutable) but then eventually another class name would have been necessary for immutable (right-hand side value). So MutableInteger
and ImmutableInteger
both can be used in programs in one form or another. However, people happen to use the latter more often. So, early on Java developers decided to use the shorter name Integer for the latter (ImmutableInteger
). There are various reasons why the latter turns out to be more useful and less error-prone that are explained well in other answers to this post. Both are possible and they both exist, just there is more demand for the latter.