What it is and why to use it
Java always passes argument values by value. For a primitive, the copied value is the number or boolean itself. For an object, the copied value is a reference to that object. Two reference variables can therefore reach the same mutable object without being the same variable.
How it works
This example adds a name through a copied list reference and then assigns the parameter a different list. The addition changes the shared original list. The reassignment changes only the method’s local parameter. This distinction helps explain surprising changes made by helper methods.
Common mistakes and limitations
Do not describe objects as being passed by reference. A method can change an accessible object’s state, but assigning its parameter does not reassign the caller’s variable. Immutable objects such as String cannot be changed through a reference.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
void update(List<String> names) { names.add("James"); }Examples
Pass-by-Value and Object References
Complete Main.java example — Java 17 or later, without preview features.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void update(List<String> names) {
names.add("James");
names = new ArrayList<>();
names.add("Alex");
}
public static void main(String[] args) {
List<String> learners = new ArrayList<>(List.of("John"));
update(learners);
System.out.println(learners);
}
}- learners initially refers to a mutable list containing John.
- update receives a copy of that reference; names.add("James") modifies the object both references reach.
- Assigning a new ArrayList to names leaves learners pointing at the original list, so Alex is absent from the printed output. Return a new value when replacement is the intended operation.
- Expected output: [John, James]
Best practices
- State whether a method mutates its arguments.
- Return replacement values explicitly.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification