Why does Java evaluate 1000==1000 as false while 100==100 evaluates to true?
The article explains that Java's Integer caching for values between -128 and 127 causes small integer objects to be shared, making == true for 100, whereas larger integers like 1000 are distinct objects, so == returns false, and it demonstrates this behavior with code and reflection examples.
In Java, the == operator compares object references, not their numeric values. When two Integer objects refer to the same cached instance, == returns true; otherwise it returns false.
Running the following code illustrates the difference:
Integer a = 1000, b = 1000;
System.out.println(a == b); //1
Integer c = 100, d = 100;
System.out.println(c == d); //2produces the output:
false
trueThe reason is that Java caches Integer objects for the range -128 to 127 in an internal class IntegerCache. Assignments such as Integer c = 100; are actually compiled to Integer i = Integer.valueOf(100); and valueOf returns a cached instance when the value lies within the cache range:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) {
return IntegerCache.cache[i + (-IntegerCache.low)];
}
return new Integer(i);
}Consequently, both c and d reference the same cached object, making c == d evaluate to true. For values outside the cache (e.g., 1000), new objects are created, so a == b is false.
The article also shows how to manipulate the cache via reflection:
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);
}This demonstrates that the cache can be altered, which may affect the result of == comparisons for cached values.
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.
IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
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.
