• 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

immutable

 
D H
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings, boolean, and double are all supposed to be immutable, supposedly meaning that their values can't be changed. In the code that I write, I have no problem changing the values of any of these types. I must be missing something. Can someone please explain.
example:
double testdouble = 5.0;
testdouble += 6.0;
testdouble = 7.5;
it all works fine. How can this be immutable if the above example doesn't even produce and error?
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have made two incorrect assumptions:
1. boolean and double are primitive types, not objects. They are not immutable. Their corresponding object wrappers Boolean and Double are immutable, however.
2. A variable that holds a reference to an object is not the same as the object itself. For example:
String s = "Hello, world";
String t = "Goodbye, world";
String u = s;
System.out.println(u); // Prints "Hello, world"
u = t;
System.out.println(u); // Prints "Goodbye, world"
The String variable u first refers to the String whose value is "Hello, world", but you can easily change it to point to a different string. You have not changed the String object "Hello World" at all - it is indeed immutable.
Similarly:
String s = "";
s = s + "Hello";
s = s + " ";
s = s + "World";
has a number of different String objects, all of them immutable. Each time you assign a new value to s, it is simply pointing to a different object.

------------------
Phil Hanna
Author of :
JSP: The Complete Reference
Instant Java Servlets
[This message has been edited by Phil Hanna (edited April 15, 2001).]
 
reply
    Bookmark Topic Watch Topic
  • New Topic