This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Are Wrapper Classes always Immutable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Are Wrapper Classes always Immutable" Watch "Are Wrapper Classes always Immutable" New topic

Are Wrapper Classes always Immutable

Nigel Slinn

Joined: Aug 04, 2005
Posts: 1
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

Joined: Feb 05, 2001
Posts: 17271

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.


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
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

Joined: Jun 13, 2005
Posts: 335
I do know String is not a wrapper class but just to give an example.
Have you checked out Aspose?
subject: Are Wrapper Classes always Immutable
It's not a secret anymore!