Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String classes

 
niras iva
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String is immutable:

String s="hello";

s+="bfgkjdf";

Now the value of s is changed.. then how string is immutable?please explian it clearly
 
Campbell Ritchie
Sheriff
Pie
Posts: 48943
60
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are creating a new String object"hellobfgkjdf" and substituting that for the original String. The two Strings "hello" and "bfgkjdf" still exist, but are unreachable because their references are changed.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12123
30
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because s is not a string. it is a REFERENCE to a string. The String object "hello" still exists unchanged, but you no longer have a reference variable pointing to it.

It is similar to having an address card that points to a house. you can change the address written down on the card, but the original house is unchanged.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48943
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
niras iva,
Your post was moved to a new topic.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48943
60
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I earlier wrote:niras iva,
Your post was moved to a new topic.
That was because you added an unrelated question to an old thread.
 
John Hua
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should know the String class was defined as public final class String.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48943
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic