Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Are Wrapper Classes always Immutable

 
Nigel Slinn
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The guide I am reading contradicts itself, so what is the official line.

It quotes something like.
All wrapper objects are immutable. Once an object is created, the wrapped primitive value cannot be changed.

However the code below produces 2 different values:
Short wrapped = Short.valueOf((short)2);
short shorty = 3;
System.out.println("Short " + wrapped);
wrapped = shorty;
System.out.println("Short " + wrapped);
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wrapped = shorty;


This line here uses autoboxing, so it actually creates a new Short wrapper object, so there are two different objects, and the prints will print different results.

The wrapper object is still immutable.

Mark
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nigel I dont know 1.5 but I know 1.4

See Strings objects are immutable, reference variable are not.

String s=new String("Hello");
String s1=new String("World");
s=s1; // now s points to String "World"
// Hello did not change

so objects are immutable means their value cant be changed but
reference pointing to them can change as reference are not immutable.

same with wrapper,

hope this helps correct me if so think so.
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do know String is not a wrapper class but just to give an example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic