πŸ”Ή Java is Pass-by-Value: What It Really Means



This content originally appeared on DEV Community and was authored by Mohamad mhana

Have you ever wondered why modifying a method parameter doesn’t always change the original variable in Java?

This is because Java is always pass-by-value. Let’s break it down.

1⃣ What Does Pass-by-Value Mean?

When you pass a variable to a method, Java makes a copy of the value and sends it to the method.

Primitive types (int, double, boolean) β†’ method works on the copy, original stays unchanged.

Objects β†’ method receives a copy of the reference. You can modify the object’s contents, but reassigning the reference won’t affect the original object.

Think of it like sending a photocopy of a key. You can open the door (modify the object), but replacing the key (reassigning the reference) won’t change the original.

2⃣ Example 1: Primitives

int x = 10;
modifyPrimitive(x);
System.out.println(x); // Output: 10

void modifyPrimitive(int number) {
    number = 20;
}

βœ… Explanation: number is a copy of x, so changing it inside the method does not affect x.
βœ… Enforces: Understanding of primitive types and variable scope.

3⃣ Example 2: Objects

Person person = new Person("Mohammed");
modifyObject(person);
System.out.println(person.name); // Output: Ali

void modifyObject(Person p) {
    p.name = "Ali"; // Modifies the object itself
}

βœ… Explanation: Method gets a copy of the reference, so you can modify the object’s state.
βœ… Enforces: Understanding objects vs references.

4⃣ Example 3: Reassigning Objects

Person person = new Person("Mohammed");
reassignObject(person);
System.out.println(person.name); // Output: Mohammed

void reassignObject(Person p) {
    p = new Person("Ali"); // Only reassigns inside method
}

βœ… Explanation: Reassigning the reference does not affect the original object.
βœ… Enforces: Understanding pass-by-value vs pass-by-reference confusion.

5⃣ Key Takeaways

Everything in Java is pass-by-value.

Primitives: method gets a copy β†’ original value unchanged.

Objects: method gets a copy of the reference β†’ can modify object contents but not the original reference.

Knowing this prevents bugs and confusion when passing variables to methods.

Have you ever been confused why modifying an object in a method sometimes works and sometimes doesn’t?

Can you think of a scenario where misunderstanding pass-by-value could break your code?

Share your thoughts in the comments! πŸš€

πŸ“š Resources:

Baeldung – Java Pass by value

GeeksforGeeks – Java is always Pass by Value


This content originally appeared on DEV Community and was authored by Mohamad mhana