Beyond Syntax - By Thinking Room Co.’s Post

This Java code runs without errors. Both comparisons look identical. But one prints true and the other prints false. Can you tell me why? 👇 — — — Most Java engineers who see this either: A) Say "use .equals() not ==" — which is true, but misses the deeper reason entirely B) Have no idea and quietly Google it The real answer has nothing to do with best practices. It's about something the JVM does silently, automatically, on every Java program ever run. Something most Java engineers use every day without knowing it exists. Drop your answer below. Tomorrow I'll post the full explanation — with exactly what's happening under the hood and why the JVM was designed this way. — — — This is the kind of thing we go deep on at Beyond Syntax — not just the what, but the why behind every design decision. Follow for weekly Java deep-dives like this. #Java #SoftwareEngineering #BeyondSyntax #JVM #Programming #CodeReview #Bengaluru

  • graphical user interface, text

The JVM caches Integer objects between -128 and 127. So when you write Integer a = 127, Java reuses the same object from cache. a == b compares references — and since both point to the same cached object, it returns true. But 128 is outside the cache range, so Integer c = 128 creates a brand new object each time. c and d are different objects in memory — same value, different references. That's why c == d is false. This is the Integer Cache, defined in the Java Language Specification. It exists for performance — small integers are used constantly, caching them avoids millions of unnecessary object allocations. The fix is always .equals() for object comparison — but now you know WHY.

Like
Reply

To view or add a comment, sign in

Explore content categories