• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Are Wrapper Classes always Immutable

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I do know String is not a wrapper class but just to give an example.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic