Topic 19 of 30 · Beginner
Can a Java method replace the caller’s object reference?
Java passes all arguments by value. For object arguments, the copied value is a reference, so a method can mutate the referenced object but cannot rebind the caller's variable.
Java 17+; compile each complete program as Main.java.
Detailed answer
Java passes all arguments by value. For object arguments, the copied value is a reference, so a method can mutate the referenced object but cannot rebind the caller's variable.
Assigning a new object to the parameter changes only the method's local reference. Changes through the original reference remain observable if the object is mutable.
Primitive arguments are also copied. Returning a new value or using a documented mutable holder is preferable to assuming pass-by-reference behavior.
Internal working
A method stack frame receives copies of argument values; objects can remain shared on the heap through several references.
Practical scenario
An API tries to reset a caller's List by assigning the parameter to new ArrayList; the caller still sees the old list.
import java.util.*;
class Main { static void reset(List<Integer> x){x = new ArrayList<>();} public static void main(String[] a){var x = new ArrayList<>(List.of(1)); reset(x); System.out.println(x);}}Common mistakes
- Calling Java pass-by-reference.
- Confusing mutation with reassignment.
Key takeaways
- All arguments are copied values.
- References may share mutable objects.
- Return replacement objects explicitly.
Follow-up challenges
- How do immutable objects affect this example?
- What changes for primitive parameters?