Fundamentals 3 min read

Why Does 1000 == 1000 Return false but 100 == 100 Return true in Java?

The article explains that Java's Integer caching makes 1000 == 1000 false while 100 == 100 true, detailing how the IntegerCache works, why == compares references, and how reflection can expose the private cache array.

IoT Full-Stack Technology
IoT Full-Stack Technology
IoT Full-Stack Technology
Why Does 1000 == 1000 Return false but 100 == 100 Return true in Java?

Running the code shows false for 1000 == 1000 and true for 100 == 100.

In Java, the == operator compares object references; two distinct Integer objects are unequal even if they hold the same value.

The surprising true result for 100 comes from the IntegerCache inside Integer.java, which caches Integer objects for values between -128 and 127.

When an Integer literal in that range is created, the compiler uses Integer.valueOf(int), which returns the cached instance if the value lies within the cache bounds:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

Thus the two variables c and d both reference the same cached object, making c == d evaluate to true.

The cache reduces memory usage because small integers are used far more frequently than larger ones.

The article also shows how to access the private cache via reflection, allowing manipulation of the cached array:

Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[132] = newCache[133];
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b);
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaReflectionCachingReference EqualityInteger
IoT Full-Stack Technology
Written by

IoT Full-Stack Technology

Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.