Why Does 1000 == 1000 Return false While 100 == 100 Returns true in Java?
In Java, comparing two Integer objects with == yields false for 1000 but true for 100 because the language caches small integer instances (-128 to 127) via Integer.valueOf, causing both variables to reference the same object only within that range.
Running the following code demonstrates a surprising result:
Integer a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 100, d = 100;
System.out.println(c == d);The output is:
false
trueThe == operator on object references checks whether the two references point to the exact same object. Therefore, two distinct Integer instances are unequal even if they hold the same numeric value.
Inside the JDK, the Integer class contains a private static inner class IntegerCache that pre‑creates and stores Integer objects for every value from -128 to 127. When Integer.valueOf(int i) is called, it returns the cached instance if i lies within that range; otherwise it creates a new object.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}Consequently, the variables c and d both receive the same cached object for the value 100, so c == d evaluates to true. The variables a and b fall outside the cache range, each receiving a distinct object, making a == b evaluate to false.
The cache exists because small integers are used far more frequently than larger ones, and reusing the same object reduces memory allocation overhead.
Using reflection you can bypass the cache and modify its internal array, which may lead to unexpected behavior:
Class cache = Integer.class.getDeclaredClasses()[0]; // IntegerCache class
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[132] = newCache[133]; // corrupt cache entryThe example then prints a simple arithmetic expression to show the program still runs, but the cache manipulation illustrates how reflection can misuse this optimization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
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.
