Skip to main content

🚚 Pass By Value vs Pass By Reference in Java — The Great Confusion Buster πŸ’£

 

πŸ’¬ “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:


public void change(int x) { x = 10; }

“Cool, this is pass-by-value. Just a copy. I get it.” ✅

But then...


public void update(User u) { u.setName("Anand"); }

“Wait, it changed outside! That must be pass-by-reference!” ❓

And then...


public void update(User u) { u = new User("NewGuy"); }

“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


public void change(int x) { x = 10; } int a = 5; change(a); System.out.println(a); // prints 5 ❌ no change

πŸ“¦ Memory (Stack Only — Primitives)

Stack: ----------- | a = 5 | // main method variable ----------- | x = 5 | // method receives a copy ----------- Inside method: x = 10; // Only updates local copy. No effect on 'a'

🧠 What happened? Java passed the value 5 to x, changed x to 10, but a is untouched.


πŸ”Ή Example 2: Object Reference – Mutating Object


public void update(User u) { u.setName("Anand"); } User user = new User("Old"); update(user); System.out.println(user.name); // prints "Anand" ✅ changed

πŸ“¦ Memory (Stack + Heap)


Stack: Heap: ---------- ------------------- | user | ----ref----> | User object | ---------- | name = "Old" | ------------------- Inside method: ---------- ------------------- | u | ----ref----> | same User object | ---------- ------------------- After u.setName("Anand"): Heap: ------------------- | name = "Anand" | ✅ updated! -------------------

🧠 What happened? Java passed a copy of the reference. You didn’t change the reference — you modified the object it points to. So changes are visible outside.


πŸ”Ή Example 3: Object Reference – Reassigning Object


public void update(User u) { u = new User("NewGuy"); } User user = new User("Old"); update(user); System.out.println(user.name); // prints "Old" ❌ no change

πŸ“¦ Memory (Stack + Heap)


Before reassignment: Stack: Heap: ---------- ------------------- | user | ----ref----> | User object | ---------- | name = "Old" | ------------------- Inside method: ---------- ------------------- | u | ----ref----> | same User object | ---------- ------------------- Now we do: u = new User("NewGuy"); After reassignment: Stack: ---------- ------------------- ------------------- | u | --ref--> | User("NewGuy") | ✅ new object ---------- ------------------- ------------------- BUT... user in main() still points to: ------------------- | name = "Old" | ❌ unchanged -------------------

🧠 What happened? You created a new object inside the method and made u point to it — but user in the calling method is still pointing to the old one.

 


πŸ€” 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):


void swap(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; }

❓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


public void reset(Config c) { c = new Config(); // thought this reset everything }

The dev thought this resets the config across the app.
But it only changed the local reference.
The global config stayed stale. 🀦‍♂️

Fix:

public void reset(Config c) { c.clear(); // actually mutate the object }

🎨 Wrapping Up 

ConceptJava 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

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🧡 Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

πŸš€ “How are Virtual Threads different from Thread Pools?” 😡 “Are they OS threads or JVM threads?” πŸ™ƒ “Should I still use CompletableFuture?” 🀯 “How do I even use them in real-time microservices?” 🧠 What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. 🧠 What is the OS Kernel? πŸ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory 🧠 Schedules threads πŸ•’ Talks to hardware πŸ’» Handles I/O operations πŸ“¨ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. πŸ–Ό️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...