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

Leave a Comment