• Post Reply Bookmark Topic Watch Topic
  • New Topic

immutable

 
D H
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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?
 
Phil Hanna
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • 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).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!