Have you tried compiling this? I see at least 10 typos. Remember, Java is case sensitive, and parentheses and braces are quite different. The output is actually javajavaC (and that 'C' was probably intended to be lowercase).
The idea illustrated here is that Strings are immutable. When you call myString.replace('a', 'b'), the original String is not changed in any way. Instead, a new String is created with the replaced chars.
In contrast, a StringBuffer is mutable. When you call myStringBuffer.append("Str"), the original StringBuffer's contents is appended with the argument String.
Therefore, the output will be the original String, unchanged by the call to replace, concatenated with a String representation of the StringBuffer, which has been changed to include the appended "c".
So the result is "java" and "javac." (Get it? ) [ July 28, 2007: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Feb 17, 2007
Thanks Buddy.Looks like the question was improperly typed on the simulator.Thanks anyway.Appreciate your help.
On the exam they will give you some complicated code with a method that takes in a String and changes it locally in the method. The method returns void. It's a trick. If you pass into a method any immutable object (String, Integer, etc) you will not be able to change the underlying object and the original reference variable will be pointing to the original (and unchanged) object. In the case of a String any attempt to change it will result in a new String object being created.
Originally posted by Michael Ku: ... It's a trick...
It's testing knowledge of String methods and local variable scope. I'm not sure that's a "trick." It's just something you need to know.
Joined: Apr 20, 2002
The trick is not the concept. The trick is that if you do not recognize early if not immediately that the String cannot be changed then you waste valuable time trying to figure out the "changes" to the String