Understanding Java Integer Caching: Why 1000 == 1000 Is False but 100 == 100 Is True
The article explains that Java's Integer objects use an internal cache for values between -128 and 127, causing equality checks with the == operator to return true for small numbers like 100 but false for larger numbers like 1000, and demonstrates how to inspect and manipulate this cache via reflection.
Why does Integer comparison 1000 == 1000 evaluate to false while 100 == 100 evaluates to true in Java? This is an interesting discussion topic.
If you run the following code:
Integer a = 1000, b = 1000;
System.out.println(a == b); //1
Integer c = 100, d = 100;
System.out.println(c == d); //2You will get:
false
trueBasic knowledge: two references are equal with == only when they point to the same object; otherwise they are considered unequal even if their contents are identical.
Therefore the second statement might also be expected to be false , but it is not.
The reason lies in Integer.java , which contains a private inner class IntegerCache that caches all integer objects in the range -128 to 127.
All small integers are cached, so when we write something like:
Integer c = 100;the compiler actually executes:
Integer i = Integer.valueOf(100);Looking at the valueOf() method reveals:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) {
return IntegerCache.cache[i + (-IntegerCache.low)];
}
return new Integer(i);
}If the value is within -128 to 127, the method returns the cached instance.
Thus the statements:
Integer c = 100, d = 100;point to the same cached object, making c == d evaluate to true .
Why is this cache needed? Small integers are used far more frequently than large ones, so reusing the same underlying objects reduces memory consumption.
However, the cache can be misused via reflection. The following code demonstrates accessing and modifying the cache:
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0]; //1
Field myCache = cache.getDeclaredField("cache"); //2
myCache.setAccessible(true); //3
Integer[] newCache = (Integer[]) myCache.get(cache); //4
newCache[132] = newCache[133]; //5
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b);
}Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.