The thing to consider here is that variables representing method parameters are local to the method. So "text" is local to the method stringReplace. At first, it references the same String object as "textString." But inside the method, "text" is reassigned to reference a new String produced by text.replace('j', 'c'). This assignment has no effect on the original String that's still referenced by "textString."

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummersscce.org

Ls chin

Ranch Hand

Posts: 99

posted 9 years ago

Thank you, Henry & marc,

Java object references are passed by value, i.e. it pass a 'copy' of the value to the method, therefore the original value is not changed. Ahhh, I see. No wonder it still prints "java".

I refactored the code to make it print "cava" by changing the void method to return a String value and then print that return value. Is that the correct way to replace a char in a String?

The code that I gave in the OP came from an SCJP mock exam. I think that question was designed to "purposely" confuse us - making us think that the output would be "cava" but in fact, it is still "java".