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
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.
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
Joined: Aug 16, 2003
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.