Member-only story
Is Java Pass-by-Value or Pass-by-Reference?
If you’re confused whether Java is pass-by-value or pass-by-reference, you’re not alone. This is one of the most misunderstood topics in Java, especially among beginners and even experienced developers preparing for interviews.
Let’s simplify the answer with examples. ✅
✅ Quick Answer:
Java is always pass-by-value.
Yes — even when you pass objects.
But… it behaves a bit differently when you pass objects compared to primitive types, which causes the confusion.
Let’s explore both.
🔹 What is Pass-by-Value?
Pass-by-value means a copy of the variable is passed to the method. Changes made to the copy do not affect the original.
🔸 What is Pass-by-Reference?
Pass-by-reference means the reference (memory address) itself is passed. So any changes affect the original object or variable.
🚀 Java Pass-by-Value: Explained
In Java, when you pass a variable to a method, Java creates a copy of that variable’s value and passes it.
This is true for:
- Primitive types → copy of the value
- Objects → copy of the reference
Let’s see both with examples 👇
1️⃣ Example with Primitive Type (int, boolean, etc.)
public class Test {
public static void modify(int x) {
x = 100;
}
public static void main(String[] args) {
int num = 50;
modify(num);
System.out.println(num); // Output: 50 ❌ Not changed
}
}
🔍 Explanation:
A copy of num
is passed to the modify()
method. The original num
remains unchanged.
2️⃣ Example with Objects
class Student {
String name;
}
public class Test {
public static void update(Student s) {
s.name = "Priya"; // modifying internal field
}
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Amit";
update(s1);
System.out.println(s1.name); // Output: Priya ✅ Changed
}
}