📦 What gets passed?
Type | What gets passed? |
---|---|
Primitives (int, double, boolean, etc.) | The actual value (a copy of the primitive itself) |
Objects (String, List, etc.) | A copy of the reference to the object (not the object itself) |
🔥 What does this mean practically?
✅ Example 1 — Primitives
public class PassByValueDemo {
public static void main(String[] args) {
int number = 5;
changePrimitive(number);
System.out.println(number); // Still 5 (original unaffected)
}
static void changePrimitive(int num) {
num = 10; // This only changes the local copy
}
}
number
is passed by value, meaning a copy of 5 is passed into changePrimitive
.The num
variable inside changePrimitive
is independent of the original number
.
✅ Example 2 — Objects (The Confusing Part)
public class PassByValueDemo {
static class Person {
String name;
Person(String name) {
this.name = name;
}
}
public static void main(String[] args) {
Person person = new Person("Alice");
changePerson(person);
System.out.println(person.name); // Bob
}
static void changePerson(Person p) {
p.name = "Bob"; // This changes the actual object's field
}
}
person
is passed by value, meaning a copy of the reference is passed tochangePerson
.- Both
person
(inmain()
) andp
(inchangePerson()
) point to the same object. - So modifying fields inside the object works.
❌ What doesn’t work (Reassigning the reference itself)
static void changePerson(Person p) {
p = new Person("Charlie"); // This only changes the local copy of the reference
}
This doesn’t affect the original person
in main()
, because the reference itself is passed by value.Only p
now points to Charlie
, but person
in main()
still points to Alice
.
✅ Rule to Remember
Type | What gets passed? | Can you change the original? |
---|---|---|
Primitive | Copy of value | ❌ No |
Object Reference | Copy of reference | ✅ Yes, if you modify the object’s internal state (fields) |
Object Reference | Copy of reference | ❌ No, if you reassign the reference itself |
📊 Quick Analogy
Think of it like giving someone a copy of your house key.
- They can use the key to change things inside the house (furniture, painting the walls) — this is modifying fields inside the object.
- But if they throw away the key and create a new house, your original house is unaffected — this is reassigning the reference.
⚠️ Important Misconception
❌ Java is pass-by-reference for objects. (This is wrong!)
✅ Java is always pass-by-value — but what gets passed is a copy of the reference, not the object itself.
📚 Summary
Concept | Primitives | Objects |
---|---|---|
Passed as | Copy of value | Copy of reference |
Changing the object itself | N/A | Affects original object |
Reassigning the parameter | No effect on original | No effect on original |