Java Method Parameters: Pass by Value Explained
Java always passes arguments by value, including object references. See why a method can't change a primitive argument, why it can change an object's state, why a swap method can't work, how this differs from C++ references, and how to return several results instead.
kvi5hnuCode Sprout team member8 min readOn this page
"Is Java pass-by-value or pass-by-reference?" is one of the most frequently asked Java questions, and a favorite in interviews. The answer is short: Java is always pass-by-value. Understanding what that means for object references takes a little more work, and that's what this article is about.
Two Ways a Language Can Pass Arguments
Language designers describe argument passing with two classic terms:
- Call by value: the parameter is a new variable that starts out holding a copy of the argument's value.
- Call by reference: the parameter is an alias for the caller's variable, so assigning to the parameter assigns to the caller's variable.
Java only does call by value. Every parameter is a fresh local variable filled with a copy. One consequence follows directly: no method can make a caller's variable hold something else.
int lateDays = 3;
omar.logLateDays(lateDays);
// lateDays is 3 here, whatever logLateDays does with its parameter
Primitive Parameters
Here is a method that tries to add a bonus to a score:
static void addBonus(int points) { // has no effect on the caller
points = points + 15;
}
Called like this:
int score = 60;
addBonus(score);
score is still 60 afterwards. What happens, in order:
- A new variable
pointsis created and receives a copy ofscore, so it holds 60. pointsbecomes 75. Nothing links it toscore, soscorestays 60.- The method returns and
pointsis gone.
Object Parameters
The other kind of parameter is an object reference, and here the picture changes. This method really does double an employee's salary:
static void doubleSalary(Employee e) { // the caller sees the change
e.giveRaise(100);
}
omar = new Employee(...);
doubleSalary(omar);
- The parameter
ereceives a copy ofomar. What gets copied is the reference, not the object. eandomarnow point at one and the sameEmployee. CallinggiveRaise(100)throughechanges that object.- When the method returns,
edisappears, but the object it modified is still the objectomarpoints to, with its salary now doubled.
So a method can freely modify the object a parameter points to. Copying the reference gives the method a second way to reach the same object, nothing more.

The Swap Test
People often summarize the previous section as "objects are passed by reference". That summary is wrong, and a swap method shows why. C++ and Pascal, for example, really do offer reference parameters, and with them a swap works. In Java:
static void swap(Employee first, Employee second) { // swaps only the local copies
Employee held = first;
first = second;
second = held;
}
var mina = new Employee("Mina", ...);
var theo = new Employee("Theo", ...);
swap(mina, theo);
// mina still refers to Mina, theo still refers to Theo
Inside swap, first and second are copies of the two references. Exchanging the copies works perfectly, and then the method returns and throws them away. The caller's variables mina and theo were never touched.
With real call by reference, the caller's variables would have been exchanged. They weren't, so the conclusion is clear: Java passes object references by value.
Seeing All Three Cases Run
public class Solution {
public static void main(String[] args) {
System.out.println("-- primitive --");
int score = 60;
System.out.println("caller before: score=" + score);
addBonus(score);
System.out.println("caller after: score=" + score);
System.out.println("-- object state --");
var omar = new Employee("Omar", 52000);
System.out.println("caller before: salary=" + omar.getSalary());
doubleSalary(omar);
System.out.println("caller after: salary=" + omar.getSalary());
System.out.println("-- swap --");
var mina = new Employee("Mina", 61000);
var theo = new Employee("Theo", 57000);
swap(mina, theo);
System.out.println("caller after: mina=" + mina.getName() + ", theo=" + theo.getName());
}
static void addBonus(int points) {
points = points + 15;
System.out.println("inside: points=" + points);
}
static void doubleSalary(Employee e) {
e.giveRaise(100);
System.out.println("inside: salary=" + e.getSalary());
}
static void swap(Employee first, Employee second) {
Employee held = first;
first = second;
second = held;
System.out.println("inside: first=" + first.getName() + ", second=" + second.getName());
}
}
class Employee {
private String name;
private double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
String getName() { return name; }
double getSalary() { return salary; }
void giveRaise(double pct) {
salary += salary * pct / 100;
}
}
-- primitive --
caller before: score=60
inside: points=75
caller after: score=60
-- object state --
caller before: salary=52000.0
inside: salary=104000.0
caller after: salary=104000.0
-- swap --
inside: first=Theo, second=Mina
caller after: mina=Mina, theo=Theo
In the first case the change stays inside the method. In the second it is visible to the caller, because both references lead to the same object. In the third the method exchanges its own copies, and the caller's variables keep pointing where they did.
The Three Rules
Here's what you can and can't do with method parameters in Java:
| Possible? | |
|---|---|
A method modifies a parameter of primitive type (numbers, char, boolean) so that the caller sees it | No |
| A method changes the state of an object passed as a parameter | Yes |
| A method makes an object parameter refer to a new object so that the caller sees it | No |
The same rules apply to arrays, which are objects: a method can change the elements of an array argument, but assigning a new array to the parameter has no effect on the caller. And since strings are immutable, a method that receives a String can't change the caller's string in any way:
import java.util.Arrays;
public class Solution {
static void fill(int[] a) {
a[0] = 99; // changes the caller's array
}
static void replace(int[] a) {
a = new int[] {7, 7}; // only changes the local copy of the reference
}
static void shout(String s) {
s = s.toUpperCase(); // new string assigned to the local copy
}
static void exclaim(StringBuilder b) {
b.append("!"); // mutates the shared object
}
public static void main(String[] args) {
int[] arr = {1, 2};
fill(arr);
replace(arr);
System.out.println(Arrays.toString(arr));
String s = "hi";
shout(s);
System.out.println(s);
StringBuilder b = new StringBuilder("hi");
exclaim(b);
System.out.println(b);
}
}
[99, 2]
hi
hi!
What to Do Instead
Since a method can't change its caller's variables, use these patterns:
- Return the new value instead of trying to modify a parameter:
score = withBonus(score);. This is usually the cleanest solution. - Return several values in one object. A small record (covered two articles from now) is ideal:
record MinMax(int min, int max) {}
static MinMax minMax(int[] values) {
int lo = values[0], hi = values[0];
for (int v : values) {
lo = Math.min(lo, v);
hi = Math.max(hi, v);
}
return new MinMax(lo, hi);
}
// minMax(new int[] {3, 9, 1}) returns MinMax[min=1, max=9]
- Make it a method of the object whose state should change (
omar.giveRaise(100)), which is what encapsulation suggests anyway. - Swapping in Java is done where the variables live, e.g., swapping two array elements inside the method that owns the array:
int t = a[i]; a[i] = a[j]; a[j] = t;.
Common questions
So is Java pass-by-reference for objects? No. Java passes a copy of the reference. The method can use that copy to change the object, but it can't make the caller's variable refer to a different object. That is exactly what pass-by-value means when the values are references.
Why can't I write a swap(int a, int b) method?
The method receives copies of the two values, and swapping the copies doesn't affect the caller's variables. Swap elements of an array or fields of an object inside a method instead, or simply write the three-line swap where the variables live.
Does passing a big object to a method copy the object? No. Only the reference is copied, which is a few bytes, however large the object is. Passing objects to methods is therefore cheap.
Can a method change a String argument?
No. The method can't change the caller's variable, and String objects are immutable, so there's nothing to modify. A method that "modifies" a string has to return the new string, and the caller must use the result.
Does final on a parameter change anything for the caller?
No. final on a parameter only stops the method itself from reassigning it. It is sometimes used for readability, and it was needed before Java 8 to use the parameter in anonymous classes. Since Java 8, an effectively final parameter is enough for lambdas and inner classes.
Summary
- Java always passes arguments by value: each parameter variable is initialized with a copy of the argument.
- For a primitive, the copy is the value, so the caller's variable can't change.
- For an object, the copy is a reference, so the method can change the object's state, but not which object the caller's variable refers to.
- A
swap(a, b)method on references can't work in Java; object references are passed by value, not by reference. - To produce results, return them (several at once in a record), or call a method on the object that should change.
Practice Questions
After int n = 5; increment(n); where void increment(int x) { x++; }, what is n?
Still 5. x is a copy of n's value; incrementing it doesn't affect n.
Does this change the caller's list? void clear(List<String> list) { list = new ArrayList<>(); } And this? void clear(List<String> list) { list.clear(); }
The first doesn't: it only reassigns the local copy of the reference. The second does: it calls a mutator on the shared list object, so the caller's list becomes empty.
An interviewer asks: "Are objects passed by reference in Java?" How do you answer precisely?
No. Java passes everything by value. For objects, the value passed is a reference, so the method can modify the object through that reference, but it can't make the caller's variable refer to a different object. That's why a swap method doesn't work.
Why does void rename(String s) { s = "new"; } have no effect, while void rename(Employee e) { e.setName("new"); } does?
In the first, the method reassigns its local copy of the reference, and String objects can't be modified anyway. In the second, it calls a mutator on the object that both the caller's variable and e refer to.
How would you write a method that "returns" both the quotient and the remainder of two ints?
Return an object holding both, for example a record: record DivResult(int quotient, int remainder) {} and static DivResult divide(int a, int b) { return new DivResult(a / b, a % b); }.
Previous: Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
Next: Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
Related reading
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
- Java Encapsulation: Accessors, Mutators, private Methods and final Fields
- Defining Your Own Classes in Java: Fields, Constructors and Methods
- Using Predefined Classes in Java: Objects, Object Variables and LocalDate
- Introduction to Object-Oriented Programming in Java

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.