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:
Top comments (0)