Integer Caching in Java: Why 100 == 100 but 128 != 128

Why does Integer a = 100; Integer b = 100; are equal But Not for 128? 🤔 Let’s talk about a sneaky little JVM optimization called Integer Caching, one that silently saves memory and boosts performance in your Java apps. What’s Happening Behind the Scenes? When you write:     Integer a = 100;     Integer b = 100;     System.out.println(a == b); // true Both a and b point to the same cached Integer object, no new object created! But if you do this:     Integer x = 128;     Integer y = 128;     System.out.println(x == y); // false Now they’re different objects. Why? Because Java caches Integer objects only in the range -128 to +127 by default. These are the most frequently used numbers (loop counters, indexes, etc.), so reusing them saves a lot of memory and object creation overhead. Remember == compares object references, not values. So always use:     a.equals(b) for value comparisons. #java #jvm #performance

To view or add a comment, sign in

Explore content categories