File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help with test ?...strings

 
joaquim knox
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 532
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
joaquim knox
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic