← All writing

FIELD NOTES

Demystifying Java Object References: Pass-by-Value Explained

In this note

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class PassByValueDemo {
    static class Person {
        private String name;

        Person(String name) { this.name = name; }
        void setName(String name) { this.name = name; }
        String getName() { return name; }
    }

    static void mutate(Person person) {
        person.setName("Bob");
    }

    static void reassign(Person person) {
        person = new Person("Charlie");
        person.setName("David");
    }

    public static void main(String[] args) {
        Person person = new Person("Alice");

        mutate(person);
        System.out.println(person.getName()); // Bob

        reassign(person);
        System.out.println(person.getName()); // Still Bob
    }
}

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.