Is Java pass-by-value or pass-by-reference, and what does that mean for a method that tries to modify its argument?
Java is pass by value, and it always is. There is no pass-by-reference in Java at all. Every argument is copied into the method, and the method works on its own copy.
public class Main {
public static void main(String[] args) {
int original = 10;
System.out.println("before : " + original);
tryToChange(original);
System.out.println("after : " + original);
}
static void tryToChange(int value) {
value = 99;
System.out.println("inside : " + value);
}
}
The output shows all three lines. The method prints 99 inside itself, because it is working on its own copy. The caller still prints 10 afterwards, because the original variable was never touched.
The same thing happens with an object, and this is the part that surprises people. When you pass an object, the reference is copied, and not the object. So the method gets a second reference that points at the same object. If the method changes the object through that reference, the caller sees the change. If the method points its reference at a different object, the caller does not see that at all, because the copy is the only thing that moved.
So the rule to remember is this. The value of a primitive is copied and the change is lost. The reference of an object is copied and the object is shared, so a change to the object is seen by everybody while a change of the reference is not.
The next question in this topic looks at how you use that to change an object on purpose.