aspose file tools*
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
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: 11498
    
  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: 19784
    
  20

"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: 19784
    
  20

Excellent, thank you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String are immutable?