I understand the confusion, and it's a common one when learning Java. The terminology can be tricky, but let me clarify:
Primitive Types:
- When you pass a primitive type (like
int, char, double, etc.) to a method in Java, you're passing the actual value. This is unequivocally "pass by value." Altering the parameter within the method does not affect the original variable.
Object References:
- When you pass an object to a method, you're passing a copy of the reference to that object. This is where it gets confusing: even though it feels like "call by reference," it's actually "pass by value" of the reference.
- Modifying the object through this copied reference affects the original object because both the original and the copied reference point to the same object instance. However, reassigning the reference within the method does not affect the original reference outside the method.
To reiterate:
- Primitive types in Java are passed by value: The method gets a copy of the actual value.
- Object references in Java are passed by value: The method gets a copy of the reference to the object, but both the original and the copied reference point to the same underlying object.
This subtle difference means that while you can modify the object's internal state via the reference copy, reassigning the copied reference within the method has no effect on the original reference.
Here is an example to illustrate both concepts clearly:
Primitive Type Example:
public class PrimitiveExample {
public static void modifyPrimitive(int num) {
num = 100; // This change is local to this method
}
public static void main(String[] args) {
int x = 50;
modifyPrimitive(x);
System.out.println(x); // Outputs: 50 (original remains unchanged)
}
}
Object Reference Example:
public class ObjectExample {
public static void modifyObject(MyClass obj) {
obj.value = 100; // Changes the content of the object
}
public static void reassignReference(MyClass obj) {
obj = new MyClass(); // This change is local to this method
obj.value = 200;
}
public static void main(String[] args) {
MyClass myObj = new MyClass();
myObj.value = 50;
modifyObject(myObj);
System.out.println(myObj.value); // Outputs: 100 (object state changed)
reassignReference(myObj);
System.out.println(myObj.value); // Outputs: 100 (original reference unchanged)
}
}
class MyClass {
int value;
}
Key Takeaways:
- Primitive types: The method can't alter the original value.
- Object references: The method can alter the object referred to but can't change the original reference to the object.
Thus, it's technically accurate to say Java is "always pass by value." What is passed by value can either be the actual primitive value or a copy of the object reference.