All topics
library
beginner

Pass by Value in Java

Java is ALWAYS pass by value — understand what this means for primitives and objects.

Java is strictly pass-by-value. Always. There is no pass-by-reference in Java. This is one of the most misunderstood concepts and a classic interview question.

Like giving someone a copy of your house key (reference). They can go in and rearrange furniture (modify the object). But if they throw away their copy and get a new key (reassign the reference), your key still opens the same house.

Key Concepts

1
For primitives: the value itself is copied. Modifying the parameter inside the method doesn't affect the caller's variable.
2
For objects: the reference (pointer to the object on the heap) is copied by value. The method gets a copy of the reference pointing to the same object. This means: - The method CAN modify the object's state through the copied reference (both references point to the same object). - The method CANNOT make the caller's reference point to a different object (assigning a new object to the parameter only changes the local copy of the reference).
3
The confusion arises because people see that modifying object state inside a method is visible to the caller and conclude it's pass-by-reference. But the reference itself was passed by value — the method can't reassign the caller's variable.
4
Proof: if you assign parameter = new Object() inside a method, the caller's variable still points to the original object. In true pass-by-reference (like C++ &), the caller's variable would change.
5
This is exactly like C's pass-by-value for pointers: you get a copy of the pointer, can dereference it to modify the object, but reassigning the pointer doesn't affect the caller.