This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String are immutable? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String are immutable?" Watch "String are immutable?" New topic
Author

String are immutable?

James Bellan
Greenhorn

Joined: Nov 05, 2007
Posts: 9
Hi ,

I am using a String say s = "hello" in my class. As per the immutable pattern that the value for s should not change till end of my class right?
When i do s += "world", it gives me s = "helloworld". Now the value of the object s has been changed !. Then how is this immutable.
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
you just reassign the new String Object "helloworld" to the variable 's'
the Object "hello" is lost and unreachable now

try
s.concat("world");

and you will see the string have not changed
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

or try this:

String s = "hello";
String t = s;
s += "world";

then print s and t.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
James Bellan
Greenhorn

Joined: Nov 05, 2007
Posts: 9
Hi Arad,

Thanks for that.
So you mean to say that the string "helloworld" is overrided by "hello" and this "hello" is no more available in the jvm heap.
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
no .
helloworld is completely new String object
and the variable 's' reassign to it

so "hello" object is not reachable its maybe not on the heap now or maybe still there ( depends on the GC )
James Bellan
Greenhorn

Joined: Nov 05, 2007
Posts: 9
Thanks much Arad.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

"Arad",

Please read your private messages for an important message.

Thank you,

Rob


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
DONE (:
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Excellent, thank you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String are immutable?
 
Similar Threads
How to create user defined immutable class
Ajith please clarify
String classes
Math class immutable
Immutable - Mutable