File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings immutable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings immutable" Watch "Strings immutable" New topic
Author

Strings immutable

dhanashree mangaonkar
Greenhorn

Joined: Jul 29, 2004
Posts: 2
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

Joined: Jun 10, 2004
Posts: 52
[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

Joined: Jun 10, 2004
Posts: 52
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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.


SCJP Tipline, etc.
dhanashree mangaonkar
Greenhorn

Joined: Jul 29, 2004
Posts: 2
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

Joined: Dec 20, 2001
Posts: 3271
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings immutable