In Java, when you talk about “pass by value” vs “pass by reference” for methods, the key point is:
Java is always pass-by-value — but what is passed by value depends on the type of variable.
1. Pass-by-Value (for primitives)
When you pass a primitive type (int
, double
, char
, boolean
, etc.) to a method:
- Java passes a copy of the actual value.
- Changes inside the method do not affect the original variable.
Example:
public class PassByValueExample {
public static void main(String[] args) {
int x = 5;
changeValue(x);
System.out.println("After method call: " + x); // 5
}
static void changeValue(int num) {
num = 10; // Only changes the local copy
}
}
Explanation:x
stays 5
because num
in changeValue()
is just a copy.
2. Pass-by-Value of Object References
When you pass an object to a method:
- The value being passed is a copy of the reference (memory address) to the object.
- Both the original variable and the method parameter refer to the same object.
- If you change the object’s internal state via the reference, the change is visible outside.
- But if you make the parameter point to a new object, it does not change the original variable’s reference.
Example:
class Box {
int value;
}
public class PassByReferenceExample {
public static void main(String[] args) {
Box b = new Box();
b.value = 5;
modifyObject(b);
System.out.println("After modifyObject: " + b.value); // 10
changeReference(b);
System.out.println("After changeReference: " + b.value); // still 10
}
static void modifyObject(Box box) {
box.value = 10; // modifies the actual object
}
static void changeReference(Box box) {
box = new Box(); // changes local copy of reference
box.value = 20; // affects new object only, not original
}
}
3. Summary Table
Type passed | What is passed to method | Can method change original variable? | Can method change object’s internal state? |
---|---|---|---|
Primitive | Copy of the value | ❌ No | N/A |
Object | Copy of the reference | ❌ No (can’t reassign caller’s variable) | ✅ Yes (if mutating the object) |