📘 Article Content:
One of the most common and misunderstood concepts in Java is how parameters are passed to methods — is it pass-by-value or pass-by-reference? The answer is: Java is always pass-by-value, but how this works depends on whether you're passing primitive types or object references.
Let’s break this down.
🔹 Pass-by-Value: The Core Concept
In Java, everything is passed by value. That means a method receives a copy of the variable passed in.
However, confusion arises when dealing with objects, because what’s being passed is the value of the reference, not the object itself.
🔸 Case 1: Passing Primitive Types
When you pass a primitive type (e.g., int
, float
, boolean
), the method receives a copy of the actual value. Changes inside the method do not affect the original variable.
Example:
java
public class Example {
public static void main(String[] args) {
int x = 10;
modifyPrimitive(x);
System.out.println(x); // Output: 10
}
public static void modifyPrimitive(int a) {
a = 20; // Only modifies the local copy
}
}
🧠 The variable x
remains unchanged outside the method.
🔸 Case 2: Passing Object References
When you pass an object to a method, you’re passing the value of the reference (i.e., a pointer to the object). This means both the caller and the method point to the same object in memory, so modifications to the object itself are visible outside the method.
However, reassigning the reference inside the method does not affect the original reference.
✅ Modifying the Object Through the Reference
java
public class Example {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.value = 10;
modifyObject(obj);
System.out.println(obj.value); // Output: 20
}
public static void modifyObject(MyObject o) {
o.value = 20;
}
}
class MyObject {
int value;
}
🧠 obj.value
is updated because the method operates on the same object reference.
❌ Reassigning the Reference Inside the Method
java
public class Example {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.value = 10;
reassignReference(obj);
System.out.println(obj.value); // Output: 10
}
public static void reassignReference(MyObject o) {
o = new MyObject(); // Only changes the local copy of the reference
o.value = 20;
}
}
class MyObject {
int value;
}
🧠 obj.value
remains unchanged because the method reassigns only its local copy of the reference.
✅ Summary
TypeWhat’s PassedCan Modify Original?Can Reassign Original?Primitive TypesCopy of the value❌ No❌ NoObject ReferencesCopy of the reference✅ Yes (object's data)❌ No (reference itself)
🔒 Java always passes a copy, never the original variable itself.
🧠 Key Takeaway
Java is always pass-by-value.
For objects, it passes the value of the reference, not the object itself.
Understanding this subtle distinction will save you a lot of debugging headaches and help you write more predictable Java code.