Course contentsShow
← Java
Lesson 201 of 2,8705. Methods and Function CallsFree lesson

Reference Parameters: Mutable Object State

Understand how methods can modify object state through reference parameters despite pass-by-value.

Reference Parameters: Mutable Object State

What you'll learn: How methods can change the contents of objects even though Java always passes by value.

The Core Idea

You've learned that Java is strictly pass-by-value—methods receive copies of values, not the original variables. But here's the twist: when you pass an object to a method, you're passing a copy of the reference (the memory address), not a copy of the entire object.

Think of it like giving someone a photocopy of your house address. They can't change where your house is located, but they can use that address to visit your house and rearrange your furniture!

How It Works

When you pass an object reference to a method:

  • The method gets its own copy of the reference
  • Both references point to the same object in memory
  • Changes to the object's state through either reference are visible everywhere
class Box {
    int value;
}

public static void modifyBox(Box b) {
    b.value = 100;  // Changes the object's state
}

public static void main(String[] args) {
    Box myBox = new Box();
    myBox.value = 10;
    
    modifyBox(myBox);  // Pass reference by value
    
    // myBox.value is now 100!
}

The modifyBox method received a copy of the reference, but both the original myBox reference and the parameter b point to the same Box object. When b.value is changed, it modifies the actual object.

The Key Distinction

You cannot reassign the original reference variable itself, but you can modify the object it points to.

Key Takeaway: While Java passes references by value, methods can still modify object state because the copied reference points to the same object in memory—the reference is immutable in the caller's scope, but the object it points to is mutable.