aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Changed 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 "String Changed" Watch "String Changed" New topic
Author

String Changed

Roger Zhao
Ranch Hand

Joined: Aug 05, 2003
Posts: 73
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


"There is a will,there is a way!"<br />SCJP1.4
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
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 ]

not so smart guy still curious to learn new stuff every now and then
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Changed