It actually ends up making more sense when you understand what's going on. When you pass a scalar value, it only passes the value. When you pass an Object, you are actually passing a
reference to the object, which won't be changed by the function. The object the reference points to, though, can be changed. It's a lot like passing pointers to variables in C except that Java hides some of the details. It also doesn't do what you think it will a lot of times. For instance:
Code:
public void myMethod1(String s) {
s = new String("This is a new String");
}
public void myMethod2() {
String t = new String("This is the first String");
System.out.println(t);
myMethod1(t);
System.out.println(t);
}
will print:
Code:
This is the first String
This is the first String
because myMethod1 is making s point at a new String object rather than changing the object s references. Because the parameters are passed by value, t in myMethod2 is not altered.
On the other hand, if we do this instead:
Code:
public void myMethod1(StringBuffer s) {
s.append(" This is a new String");
}
public void myMethod2() {
StringBuffer t = new StringBuffer("This is the first String");
System.out.println(t);
myMethod1(t);
System.out.println(t);
}
we'll get this output:
Code:
This is the first String
This is the first String This is a new String
because the Object t points to is being altered, not t itself.