Java Wrapper classes are supposed to be immutable. This means that once an object is being created, e.g.,
Integer i = new Integer(5);
its value cannot be changed. However, doing
i = 6;
is perfectly valid.
So, what does immutability in this context mean? Does this have to do with auto-boxing/unboxing? If so, is there any way to prevent the compiler from doing it?
Thank you
Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
Yes, they are immutable.
In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
All the wrapper classes are declared final. All the wrapper classes except Boolean and Character are sub classes of an abstract class called Number, Boolean and Character are derived directly from the Object class. Wrapper classes are immutable.
i
is a reference. Your code change the reference i
to point to a different, equally immutable, Integer
.
final Integer i = Integer.valueOf(5);
might be more useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With