Skip to lesson

Is Java Pass by Value or Pass by Reference?

"Is Java pass by value or pass by reference?" is asked in nearly every fresher round, usually followed by a swap or an array puzzle. The interviewer is checking whether you can tell changing an object from reassigning a parameter.

Model answer: always pass by value

Pass by value means a method receives a copy of each argument in its own parameter variable. For a primitive the copy is the number itself; for an object the copy is the reference to it. Java always works this way.

This program changes a primitive parameter inside a method and prints the caller's variable before and after the call.

Example 1 · A primitive parameter is a copy

PrimitiveCopy.javaJava
public class PrimitiveCopy {    static void addGrace(int marks) {        marks = marks + 5;        System.out.println("inside method: " + marks);    }
    public static void main(String[] args) {        int marks = 38;        addGrace(marks);        System.out.println("after call:    " + marks);    }}
Output
inside method: 43
after call:    38

What this code does

  • addGrace gets its own copy of 38 and changes that copy to 43.
  • The caller's marks is a different variable, so it is still 38. To keep the change, return the new value: marks = addGrace(marks);.

For an object the variable holds a reference, the address of the object, and the copy is that reference. Model answer: "Java is always pass by value. For objects the reference is copied, so the method and the caller point to the same object. The method can change that object's fields, but if it assigns a new object to the parameter, the caller does not see it."

Revise: Pass by value in Java (opens in a new tab).

Avoid saying "primitives by value, objects by reference". Interviewers treat that as the wrong answer.

Predict the output: changing a field vs reassigning

To mutate an object is to change its contents through a reference, such as s.marks = 95. Every variable that refers to the same object sees the change. Reassigning a parameter with = is different: it only moves that parameter's arrow.

Changing a field and reassigning the parameter look similar but behave differently. This program does both in one method and prints what the caller sees.

Example 2 · Changing a field vs reassigning the parameter

FieldVsReassign.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
public class FieldVsReassign {    static void addBonus(Student s) {        s.marks += 10;                      // changes the shared object    }
    static void replace(Student s) {        s = new Student("Ravi", 50);        // only the copy points elsewhere        s.marks = 99;                       // changes the new object    }
    static void shout(String text) {        text = text.toUpperCase();    }
    public static void main(String[] args) {        Student asha = new Student("Asha", 80);        addBonus(asha);        System.out.println(asha.name + " " + asha.marks);
        replace(asha);        System.out.println(asha.name + " " + asha.marks);
        String city = "pune";        shout(city);        System.out.println(city);    }}
Output
Asha 90
Asha 90
pune

What this code does

  • addBonus follows the copied reference to the same object, so the caller sees 90.
  • replace points its copy at a new Student, and shout points its copy at a new String; the caller's asha and city are untouched.

Parameter changed with = leaves the caller unchanged, even if the new object is modified afterwards. A primitive parameter changed inside the method leaves the caller unchanged too. A String or wrapper "changed" inside a method is reassigned, because they are immutable, so the caller is unchanged as well.

Predict the output

Predict what the caller sees

Read each program and pick what it prints.

Round 1 of 3

public class Round1 {
static class Student { int marks = 80; }
static void bonus(Student s) {
s.marks = s.marks + 10;
}
public static void main(String[] args) {
Student asha = new Student();
bonus(asha);
System.out.println(asha.marks);
}
}

Swap two Integers in a method: why it fails

A swap method for two Integers cannot work, because the method swaps only its own copies of the references. This program shows the failed swap and three ways that do work.

Example 3 · Swapping Integers fails; three ways that work

SwapDemo.javaJava
public class SwapDemo {    static void swap(Integer a, Integer b) {        Integer tmp = a;        a = b;        b = tmp;                            // only the copies are swapped    }
    static void swapInArray(int[] pair) {        int tmp = pair[0];        pair[0] = pair[1];        pair[1] = tmp;                      // elements of the shared array    }
    record Pair(int first, int second) {        Pair swapped() {            return new Pair(second, first);        }    }
    public static void main(String[] args) {        Integer x = 10, y = 20;        swap(x, y);        System.out.println("swap(Integer): x=" + x + " y=" + y);
        int[] pair = {10, 20};        swapInArray(pair);        System.out.println("array swap:    " + pair[0] + " " + pair[1]);
        Pair p = new Pair(10, 20).swapped();        System.out.println("return a pair: " + p.first() + " " + p.second());
        int a = 10, b = 20;        int t = a; a = b; b = t;            // or just swap where the variables live        System.out.println("in place:      " + a + " " + b);    }}
Output
swap(Integer): x=10 y=20
array swap:    20 10
return a pair: 20 10
in place:      20 10

What this code does

  • swap(Integer, Integer) exchanges its own two reference copies, so x and y stay 10 and 20.
  • The working versions change something both sides share (array elements) or hand back a new value for the caller to keep (the Pair record).

The fixes all avoid reassigning the caller's variables: swap elements inside an array, swap fields inside an object, or return the swapped pair and let the caller assign it. The strongest answer says "this is impossible in Java because of pass by value" and then gives one fix.

Order of execution

Swap two array elements

Put the steps in the order that swaps arr[0] and arr[1] safely.

Arrays passed to methods: changes are visible

An array is an object, so passing it copies the reference. This program changes an element, reassigns the parameter and sorts the array inside methods.

Example 4 · Arrays: element changes are shared, reassignment is not

ArrayParams.javaJava
import java.util.Arrays;
public class ArrayParams {    static void addGraceToAll(int[] marks) {        for (int i = 0; i < marks.length; i++) {            marks[i] += 5;                  // visible to the caller        }    }
    static void resetWrongly(int[] marks) {        marks = new int[marks.length];      // copy now points to a new array        marks[0] = 100;                     // changes the new array only    }
    static int[] grow(int[] marks, int extra) {        int[] bigger = Arrays.copyOf(marks, marks.length + 1);        bigger[marks.length] = extra;        return bigger;    }
    public static void main(String[] args) {        int[] marks = {40, 55, 70};        addGraceToAll(marks);        System.out.println(Arrays.toString(marks));
        resetWrongly(marks);        System.out.println(Arrays.toString(marks));
        marks = grow(marks, 50);        System.out.println(Arrays.toString(marks));
        Arrays.sort(marks);        System.out.println(Arrays.toString(marks));    }}
Output
[45, 60, 75]
[45, 60, 75]
[45, 60, 75, 50]
[45, 50, 60, 75]

What this code does

  • addGraceToAll and Arrays.sort change elements of the caller's array. resetWrongly builds a new array that the caller never sees.
  • Arrays cannot grow, so grow returns a new one and the caller assigns it: marks = grow(marks, 50).

Changing elements, arr[0] = 100, or sorting the array changes the caller's array too. But arr = new int[]{...} inside the method only points the copy at a new array. This is why Arrays.sort(marks) works in place, and why a method that "resizes" an array must return the new one.

Fix the error

Return the new array

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

A method must grow the array by one slot for the caller.

public class Resize {
static int[] grow(int[] marks) {
int[] bigger = new int[marks.length + 1];
System.arraycopy(marks, 0, bigger, 0, marks.length);
marks = bigger;
}
public static void main(String[] args) {
int[] marks = {45, 60};
marks = grow(marks);
System.out.println(marks.length);
}
}

Error

Resize.java:6: error: missing return statement
    }
    ^

The whiteboard explanation

When the interviewer asks you to explain it, draw two boxes and one object. This program prints the diagram you would draw on the whiteboard.

Pass by value. The caller variable s and the method parameter s are two separate boxes that each hold an arrow to the same Student object, so changing marks through either arrow is seen by both.

Example 5 · The diagram to draw

Text
Before:   caller: asha ----\                            >----> [ Student: Asha, 80 ]   (heap)          method: s -------/s.marks += 10:   both arrows see [ Student: Asha, 90 ]s = new Student("Ravi", 50):          caller: asha --------> [ Student: Asha, 90 ]          method: s -----------> [ Student: Ravi, 50 ]   (caller never sees this)
Say it like this
The arrow (reference) is copied: not the object, not the variable.

What this code does

  • Two variable boxes, one heap object: this picture explains every pass-by-value puzzle.
  • Draw it while you talk; interviewers often stop you after the second picture because the answer is clear.

Draw the caller's variable and the method's parameter, each with an arrow to the same object on the heap. Changing the object through either arrow is visible to both; moving the parameter's arrow to a new object leaves the caller's arrow untouched. Sum it up: "the arrow is copied, not the object, and not the variable."

Next step

Check your understanding

12 quick questions