Skip to main content

Posts

Showing posts with the label Java Reference

🚚 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 point...