Compare these two methods:
private static void hello(String t) { t = "hello " + t; } private static void hello(CustomStringObject o) { o.str = "hello " + o.str; }
In the first case, you assign a new value to t . This will not affect the call code - you simply change the value of the parameter, and all arguments are passed by value in Java.
In the second case, you assign a new value to o.str . This is a change in the value of the field inside the object referenced by the value o . The caller will invoke this change because the caller still has a reference to this object.
In short: Java always uses pass by value, but you need to remember that for classes the value of a variable (or even any other expression) is a reference, not an object. You do not need to use parameter passing to see this:
Foo foo1 = new Foo(); Foo foo2 = foo1; foo1.someField = "changed"; System.out.println(foo2.someField)
The second line here copies the value of foo1 to foo2 - these two variables refer to the same object, so it does not matter which variable you use to access it.
Jon skeet
source share