Jehan Jaleel wrote:Hi,
I always thought that in Java when you call a method which takes an Object as a parameter you pass a reference to that object to that method.
That is correct. The caller's value is a reference to the object. That reference value is copied and passed to the method. Now both caller and method have references to the same object. A couple of things worth nothing: 1) A Java reference is much more like a C/c++ pointer than like a C++ reference, so if you're familiar with those concepts, the naming may be confusing, and 2) The parameter passing mechanism described here is that of passing a reference by value, which is just like how C passes pointers by value, and not at all the same as passing an object by reference (though it kind of looks similar if you squint and ignore certain definitions from Java and CS).
I thought this holds true even for String since it is an object.
It does. All parameters--primitives, references, and null--are passed identically in Java. A copy is made of the caller's value and that copy is given to the method.
But the following code shows that I am wrong...
Correct. But not in the way you think you're wrong. You're correct in what you stated above. Where you're mistaken is that you seem to think that Java "pass objects by reference." It does not. Caller and method each have their own variables, both pointing at the same object. Assigning a new value to the method's variable (telling it to point to a different object) does not have any affect on the caller, because the parameter was passed by value.