aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help with test ?...strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "help with test ?...strings" Watch "help with test ?...strings" New topic
Author

help with test ?...strings

joaquim knox
Greenhorn

Joined: Aug 16, 2003
Posts: 9
Hi,
going thru a practice test I came across the following question and don't understand it:
Public class test(
Public static void stringReplace(String test)(
test = test.replace ("j", �");
)
public static void bufferReplace (StringBuffer test)(
test = test.append("C");
)
public static void main(String args[]) (
string testString = new String ("java");
StringBuffer text BufferString = new StringBuffer ("java");
stringReplace (testString);
BufferReplace(testBuffer);
System.out.println(textString + textBuffer);
)
)
The answer is javajava.
To me should be iavajavaC
Why? because String is an object not a type, and java passes ref to the
called function. The called function can manipulate the original object
thru the ref.
Thanks,
Robert
Unni Kainila
Ranch Hand

Joined: Jul 26, 2003
Posts: 45
You have lot of mistakes (spelling, names) in your code...the code won't compile as it is.
Anyway, assuming I understood what you are trying let me try to answer you question. When objects are passes to a method, it passes as reference, but the reference variables is a local copy in the method. So, if you manipulate the object, the original referenced object will be changed as well. But if you assign a new object to the local (parameter) variables, the original referenced object won't change. Also note that String is immutable.
Hanna Habashy
Ranch Hand

Joined: Aug 20, 2003
Posts: 532
hi Robert:
String Objects in Java are immutable, and variables passed by value.
when you modified the test = test.replace("j, "i"); test noe refers to a brand new object "iava". When the method return, the object is lost becuase it is not referenced anywhere else ouside the mothod.
In the case of StringBuffer, it is not immutable. When you excute" test = test.append("C"), you appened the letter C to the acual object, wheich is referenced by testBuffer rererence variable.


SCJD 1.4<br />SCJP 1.4<br />-----------------------------------<br />"With regard to excellence, it is not enough to know, but we must try to have and use it.<br />" Aristotle
joaquim knox
Greenhorn

Joined: Aug 16, 2003
Posts: 9
Thank you all very much for taking the time to answer.
I heart of the problem is that I thought objects were passed by ref, while
primatives are passed by value ( a copy of ). Thanks, again.
 
Don't get me started about those stupid light bulbs.
 
subject: help with test ?...strings