One persistent Java misconception is whether objects are passed to methods by reference or by value. The confusing part is that a method can change an object’s fields, but it cannot replace the caller’s variable by assigning a new object to its parameter.
The rule is simple: Java is always pass-by-value. When an object is passed to a method, the value copied is the reference value. Both the caller’s variable and the parameter can therefore refer to the same object.
A Java reference is not something you should describe as a raw memory address or a C-style pointer. The Java language specifies reference values; it does not require them to expose physical heap addresses.
1. Mutating the shared object
The caller and the parameter hold separate copies of the same reference value. Calling a setter through either reference changes the same object.
2. Reassigning the parameter
If the method assigns p = new Person("Charlie"), only the local parameter is changed. The caller’s variable still contains its original reference value. The newly created object can become eligible for garbage collection when no reachable reference points to it.
Runnable example
|
|
Key takeaways
- Java passes every argument by value.
- For an object argument, the copied value is the reference value.
- Mutating the object through that reference is visible to other references to the same object.
- Reassigning the method parameter does not reassign the caller’s variable.