Java's primitive wrappers are written in stone

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 IntegerString, 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.

Tony Sintes is a principal consultant at BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java 2 developer, has worked with Java since 1997.
Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more