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

String Changed

 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,all:

what is the output?
javajavaC is right!
My Question is method textString. When v call this method at L14, method variable text is the copy of textString. text and textString point to the same one object �java� who was created on L11. But when implement the L3, this only affects the text's pointed to not textString. ???
If L11 changes to
I can understand all above, but now I can't!
Thanks in advanced,
Roger
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roger,
One point to note about the difference :
String is immutable, StringBuffer is mutable.
second, when you call a method that takes object reference as parameter,
that object reference is copied & passed into the method.
In the stringreplace method, a reference to String "java" is copied & passed into the method, when text.replace() is executed, because String is immutable, the reference inside stringreplace method is then pointed to new String "iava" while origianl reference still point to "java".
(to see this, I add one more line inside stringReplace())
For bufferReplace method, as StringBuffer is mutable, the original & copied reference point to same thing.
Hope this help

[ September 07, 2003: Message edited by: chi Lin ]
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roger,
As what Chi Lin said, String objects are immutable. In short, their value could not be changed once set. This is true no matter how you defined it.
When you invoke the method stringReplace() and pass it the String object created at line 11, you actually end up with a String object pointed to by two references, namely textString and text. Graphically, it would look like this:

But when you invoke the method text.replace() at line 3, you will create a new String object, and the reference text will now point to this new object. So you will end up with something like this:

Notice that the String object created at line 11 is not changed because, as had been said, Strings are immutable.
Hope this helps.
[ September 07, 2003: Message edited by: Alton Hernandez ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic