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

Primitive Parameters: Immutability in Method Calls

See why modifying primitive parameters inside methods doesn't affect the caller's variables.

Primitive Parameters: Immutability in Method Calls

What you'll learn: You'll discover why changing a primitive parameter inside a method doesn't affect the original variable in the caller.

The Core Idea

When you pass a primitive variable to a method, Java creates a copy of that value for the method to use. Any changes you make to the parameter inside the method only affect that copy—the original variable in the calling code remains completely unchanged.

Think of it like photocopying a piece of paper. If you make edits to the photocopy, the original document stays exactly as it was. The method works with its own separate copy of the value.

Why This Happens

Remember that Java uses pass-by-value semantics. For primitive types (int, double, boolean, etc.), this means the actual numeric value is copied into the method's parameter. The parameter is a brand-new variable that exists only within the method's scope—it has no connection back to the caller's variable.

Example in Action

public class ParameterTest {
    public static void main(String[] args) {
        int x = 10;
        changeValue(x);
        System.out.println(x);  // Still prints 10!
    }

    public static void changeValue(int num) {
        num = 99;  // Only changes the local copy
        System.out.println(num);  // Prints 99
    }
}

Even though changeValue sets num to 99, the original variable x remains 10. The method received a copy of x's value, not x itself.

Key Takeaway: Modifying primitive parameters inside a method never affects the caller's variables because methods work with copies of primitive values, not the originals.