This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization 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