Search code examples
javawrapper

Are Java wrapper classes really immutable?


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


Solution

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