Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Class is not Immutable

 
Ram Pathan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can you say that strings are immutable
when you can do an operation like
String motto="Program Once"
motto=motto+"execute everywhere"
motto=motto.concat("dont bet oin it!");
(Plz refer Mughal and rasmussen page 311)
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And everyone of those creates a completely new and distinct object. You haven't created one String object... you have created three!
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rama Krishna Pathangi:
How can you say that strings are immutable
when you can do an operation like
String motto="Program Once"
motto=motto+"execute everywhere"
motto=motto.concat("dont bet oin it!");
(Plz refer Mughal and rasmussen page 311)

Because none of these operations modify a String object. Rather, each and every one of these creates a brand new String object. Take this example:

This code snippet generates the following output:

If the original String object had actually been modified, both variables would have referenced the same String. Rather, when the concat method was invoked, a new String was created and returned from that method.
The String object is, indeed, immutable.
Corey
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The methods on String objects that seems to modify them, don't do that. They just create a new String and return it. The original string object is untouched. If you assign the returned string object to the same variable, that variable just point another object. The original string didn't change.
It is the same for the + operator.
Take a look at this code:
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Paul:
And everyone of those creates a completely new and distinct object. You haven't created one String object... you have created three!

Hence the reason why String Concatenation is such an expensive operation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic