Java Integer Caching: Why == Fails

Ever wondered why this prints true 🤔 Integer x = 125; Integer y = 125; System.out.println(x == y); // true But this prints false 😮 Integer x = 250; Integer y = 250; System.out.println(x == y); // false Looks the same… but behaves differently? Let’s break it 👇 The Reason: Integer Caching Java internally caches Integer values in the range -128 to 127. So when you write: Integer x = 125; Integer y = 125; 👉 It actually uses: Integer.valueOf(125); ✔ Both variables point to the same cached object ✔ That’s why → x == y is true ⚠️ But outside the range… Integer x = 250; Integer y = 250; ❌ No caching here ❌ Separate objects are created 👉 So → x == y is false 🚨 Important Twist (Most people miss this!) Integer x = new Integer(125); Integer y = new Integer(125); System.out.println(x == y); // false ❌ new Integer() always creates a new object ❌ Caching is NOT used here 👉 Integer caching works only with: ✔ Integer.valueOf() ✔ Autoboxing (Integer x = 125) 💡 Golden Rule x.equals(y) // ✔ Always use this for value comparison Small concepts like these can make or break your interview. Did you already know this or learned something new today? 👇 #Java #Programming #JavaTips #Coding #Developers #InterviewPrep #BackendDevelopment Inspired by amazing learning content from CoderArmy, Rohit Negi and Aditya Tandon — highly recommend following their new JAVA series!

To view or add a comment, sign in

Explore content categories