Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings immutable

 
dhanashree mangaonkar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String str="hi"
str = str + "hello"
or
str=str.concat("hello")
Will result into str="hi hello"
now strings r immutable then why it's content gets changed?
 
Pal Sudarshan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[code]
str is a reference in your code that points to "hi"
str -> "hi"

Then you are assigning str to a different object (mem location)
"hi" is not the same object as "hihello"

str + "hello" is a new object, so
str -> str + "hello" "hi" now has no reference

str.concat("hello") doesn't change the str, but then you are assigning
str = str.concat("hello") to a new object.
 
Pal Sudarshan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look through the API Spec for String, you'll see that all of the methods that "change" a String really return a new String. The methods concat, replace, toUpperCase, etc. all return new String objects. They don't actually change the String you're working on, they just give you a new one back based on what you wanted to do. Look at this example:



You see, s isn't actually modified until you assign the new, returned, value to it.
 
dhanashree mangaonkar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now String str1="hi"
String str2="hi"
Both str1 and str2 denote same object
If i change str2="hello" then will str1 also point to "hello"?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by dhanashree mangaonkar:

String str1="hi"
String str2="hi"
Both str1 and str2 denote same object
If i change str2="hello" then will str1 also point to "hello"?


No. Draw yourself a picture. Here's what we start with.



Now, if we assign "hello" to str2, you end up with this:



At that point, each reference variable would reference a different String object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic