Mani Mani - 11 months ago 55
Java Question

why Integer in java is immutable

I knew Integer is immutable in Java.
But why it is designed such a way ?.

i did went through the answers .

Is Integer Immutable

i++ still working for immutable Integer in Java?

Why are Java wrapper classes immutable?

but i couldn't find the use case which is mandate the Integer as immutable

Is there any technical reasons like for String

  1. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable

  2. To support StringPool facility

  3. To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded

    I understand there are wrappers like AutomicInteger for mutable .


From the conversation , there is no universal reason which could mandate the Integers are immutable. However by doing immutable it provides some bonus as mentioned in answers
such as

from Andrey quote

possibility to cache.
Others are reducing global state
easier multithreading

Thank you every one for your time.
Please add it in comment, if you have more points.

Answer Source

You won't find a mandatory reason why java.lang wrappers must be immutable. Simply because its a design decision, they could have decided otherwise. The language designers had to chose between mutable and immutable. And they chose immutable. Thats it.

There are some compelling (IMO) reasons though to make them immutable:

Its consistent with String, the same reasoning you provided for String to be immutable apply 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 its 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)).