I know Integers are immutable in Java. But why it is designed this way?
I went through other answers before asking this question:
i++ still working for immutable Integer in Java?
Why are Java wrapper classes immutable?
But I couldn't find the use case which mandates the Integer to be immutable. Are there any technical reasons like there are for String?
- String is used as parameter in network connection, database URLs etc. It could easily be compromised if it was mutable.
- To support StringPool facility.
- To support class loading mechanism in which Strings are used as arguments. String being mutable results in a wrong class being loaded.
I understand there are wrappers like AtomicInteger
for mutable.
UPDATE:
From the conversation, there is no universal reason that could mandate the Integers being immutable. However by doing immutable it provides some bonus as mentioned in the answers.
Such as this quote from Andrey
possibility to cache.
Others are reducing global state
easier multithreading