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 always pass-by-value. There is no pass-by-reference in Java at all. When you call a method, every argument is copied into the method's own parameter, and the method operates only on its copy.
For primitives this is intuitive: the method gets its own int, and changing it cannot affect the caller's variable. For references it is subtler but the rule is identical — the method gets a copy of the reference, not the reference itself. So if the method reassigns its parameter, the caller sees nothing, because it is writing to the local copy of the pointer. If the method mutates the object the reference points at, the caller does see the change, because both references point at the same object.
public class Main {
public static void main(String[] args) {
int original = 10;
System.out.println("before : " + original);
tryToChange(original);
System.out.println("after : " + original);
int[] numbers = {1, 2, 3};
tryToChangeArray(numbers);
System.out.println("array after : " + numbers[0]);
}
static void tryToChange(int value) {
value = 99; // changes the local copy only
}
static void tryToChangeArray(int[] values) {
values[0] = 99; // mutates the shared array
}
}The output shows both halves of the rule. The int is unchanged after the call, because only the copy was modified. The array's first element is changed, because both the caller and the method hold references to the same array object and the method mutated what it points at.
The right way to say this in an interview is that Java passes object references by value. The reference is copied; the object is shared. That single sentence resolves almost every argument-passing puzzle, including the classic question about swapping two variables inside a method: it cannot work, because the method only has copies of the references and cannot redirect the caller's variables.