Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java wrapper classes really immutable?

Tags:

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

like image 940
PetrosB Avatar asked Nov 07 '10 12:11

PetrosB


People also ask

Are wrapper classes thread-safe?

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.

Are primitives immutable in Java?

Yes, they are immutable.

Is Java class immutable?

In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.

Are wrapper classes final?

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.


1 Answers

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.

like image 116
bmargulies Avatar answered Sep 27 '22 18:09

bmargulies