• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String are immutable?

 
James Bellan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12203
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or try this:

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

then print s and t.
 
James Bellan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks much Arad.
 
Rob Spoor
Sheriff
Pie
Posts: 20671
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Arad",

Please read your private messages for an important message.

Thank you,

Rob
 
Arad Chear
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DONE (:
 
Rob Spoor
Sheriff
Pie
Posts: 20671
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent, thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic