Pass-by-Value Semantics in Java (Primitives vs References)
1Concept
Java is strictly pass-by-value. When a primitive is passed, a copy of the value is created on the method's stack frame. When an object is passed, a copy of the reference address pointing to the heap object is passed. The caller's reference cannot be reassigned by the callee, but the object's internal fields CAN be mutated.
2Architecture Diagram
[ Caller Stack Frame ] [ Callee Stack Frame ] [ Heap Memory ]
ref ----------------------------------------------------------> [ UserObject ]
copy_ref -------------------> (Mutates field!)3Code Example
Core Java
public class PassByValueDemo {
static class Account {
double balance = 1000.0;
}
static void modify(Account acc, int amount) {
amount = 500; // Primitive copy modified (Caller unaffected)
acc.balance += 250.0; // Mutates heap object through copied reference
acc = new Account(); // Reassigning callee reference has NO effect on caller
acc.balance = 0.0;
}
public static void main(String[] args) {
Account myAcc = new Account();
int originalAmount = 100;
modify(myAcc, originalAmount);
System.out.println("Primitive after method: " + originalAmount);
System.out.println("Account balance after method: $" + myAcc.balance);
}
}4Expected Output
Primitive after method: 100 Account balance after method: $1250.0
5Key Takeaways
- ✓Java does NOT support pass-by-reference; it passes object references by value.
- ✓Reassigning an object reference inside a method has zero effect on the caller.
- ✓To prevent caller data mutation, pass immutable objects or return defensive copies.