You can’t alter an immutable object!
Q: I have a basic question about the Integer class. How can I modify the value of an Integer instance? There is no function setValue offered by the application programming interface.
A: The answer to your question is simple: once an Integer
instance is created, you cannot change its value.
The Integer
String
, Float
, Double
, Byte
, Long
, Short
, Boolean
, and Character
classes are all examples of an immutable class. By definition, you may not alter the value of an immutable object after its construction.
In Java, a class such as Integer
acts as a simple wrapper around its primitive counterpart — in this case, int
. The wrappers found in java.lang
allow us to treat the primitives as if they were objects. So, for example, you could not put an int
into a Vector
without wrapping it with an Integer
object first.
Immutable classes offer a number of advantages. First, a method cannot alter an immutable object in an unexpected way. Because a method cannot leave the object in some unexpected state, you avoid a number of bugs. Second, an immutable object is intrinsically thread safe. Since a thread cannot alter the object, you do not need to protect the object from concurrent thread access.
Of course, if you need to alter your Integer
instances you are out of luck. You can write your own mutable integer wrapper class for use by your own objects. However, you cannot do anything about third-party objects that return java.lang.Integer
instances.