๐ฌ “I changed the object inside a method. But when I came back… NOTHING happened.
Java, are you even listening to me?!” ๐ก
That was me. Screaming at my screen.
So I decided to dig deep: What’s really going on?
Let’s go from basics → to bugs → to JVM internals → to truth ๐ก
๐ฏ What People Think Java Does:
“Cool, this is pass-by-value. Just a copy. I get it.” ✅
But then...
“Wait, it changed outside! That must be pass-by-reference!” ❓
And then...
“Now it DIDN’T change outside?! Java, are you drunk?” ๐บ
๐ง Truth Bomb: Java is Always Pass-by-Value. No Exceptions.
Even for objects.
But here's the tricky twist:
๐ Java passes a copy of the reference when dealing with objects.
So you're not passing the object directly —
You're passing a copy of the pointer to the object.
๐ Code Time!
๐น Example 1: Primitives — True Pass-by-Value
๐ค Why Java Did This? Internals and Design Reasons
Java designers chose pass-by-value for simplicity and predictability.
-
No dangling pointers
-
No accidental object sharing
-
Easy GC (Garbage Collection)
-
No real pointer arithmetic mess like in C++
๐ Java hides pointers from us — but under the hood, everything is still pointer logic.
๐คช Silly Questions We’ve All Asked
❓Can Java ever do pass-by-reference?
Nope. Not even on Sundays. ๐
♂️
❓Then how can I simulate it?
Wrap it in another object (e.g., Holder<T>
or an array):
❓So when I change object fields — it works. But when I reassign, it doesn’t?
Yes. Welcome to Pass-by-Reference Confusion Club™
๐ฅ Real Bug from a Production App
The dev thought this resets the config across the app.
But it only changed the local reference.
The global config stayed stale. ๐คฆ♂️
Fix:
๐จ Wrapping Up
Concept | Java Does? | What Happens |
---|---|---|
Pass-by-Value (primitive) | ✅ | A copy of the value is passed |
Pass-by-Value (object reference) | ✅ | A copy of the reference (pointer) is passed |
Pass-by-Reference (like in C++) | ❌ | Not possible |
๐ So next time someone says:
“Java passes objects by reference!”
You say:
“Nah bro. Java passes references by value — big difference!” ๐
๐ก Final Tip for Interviews:
Interviewer:
“Is Java pass-by-reference or pass-by-value?”
You:
“Always pass-by-value. Even for objects — Java passes a copy of the reference. That’s why mutations work, but reassignments don’t.”
Mic drop. ๐ค
Stay curious, stay nerdy,
– Anand ๐
Comments
Post a Comment