File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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: 17276

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 - iOS Apps
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.
I agree. Here's the link:
subject: Are Wrapper Classes always Immutable
It's not a secret anymore!