Pass by Value

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Java is STRICTLY Pass-by-Value. There is no “Pass-by-Reference” in Java.
  • When you pass a primitive to a method, a copy of the actual value is passed.
  • When you pass an Object to a method, a copy of the reference (the memory address) is passed.

Concept

This is one of the most misunderstood concepts in Java. Many developers mistakenly believe that Java passes objects by reference.

When you pass an object variable to a method, the variable holds a memory address pointing to the object on the heap. Java takes that memory address, makes a copy of it, and passes the copy to the method.

  • Because the copied reference points to the same object on the heap, you can mutate the object (e.g., change person.name).
  • However, you cannot reassign the object (e.g., person = new Person()). Doing so only changes the local copy of the reference, not the original reference in the calling method.

Examples

public class PassByValue {
    
    public static void main(String[] args) {
        int x = 5;
        modifyPrimitive(x);
        System.out.println(x); // Outputs 5 (original is unaffected)
        
        StringBuilder sb = new StringBuilder("Hello");
        mutateObject(sb);
        System.out.println(sb); // Outputs "Hello World" (Object was mutated)
        
        reassignObject(sb);
        System.out.println(sb); // Still outputs "Hello World" (Reassignment failed)
    }

    static void modifyPrimitive(int num) {
        num = 10; // Only changes the local copy
    }
    
    static void mutateObject(StringBuilder builder) {
        builder.append(" World"); // Modifies the object the reference points to
    }
    
    static void reassignObject(StringBuilder builder) {
        // Pointing the local reference copy to a brand new object
        builder = new StringBuilder("Goodbye"); 
    }
}

Interview Questions

Q: Is Java Pass-by-Value or Pass-by-Reference?
A: Java is strictly pass-by-value. For object references, it passes the value of the reference. It does not pass the reference itself.

Q: How can I swap two objects in a method?
A: You cannot. Because Java passes copies of references, if you write a swap(Object a, Object b) method and swap the references inside the method, it only swaps the local copies. The original variables in the calling method remain unchanged.