Why Does 1000==1000 Return False but 100==100 Return True in Java?

This article explains why the == operator yields false when comparing two Integer objects with the value 1000 but true for the value 100, covering Java's reference comparison, the IntegerCache mechanism, its performance rationale, and a reflective hack that can even make 2+2 equal 5.

ITPUB
ITPUB
ITPUB
Why Does 1000==1000 Return False but 100==100 Return True in Java?

Basic Knowledge Review

In Java, the == operator compares object references, not their numeric values. Two distinct Integer objects will be considered unequal even if they hold the same value, unless they refer to the exact same instance in memory.

Integer Cache Mechanism

Java's Integer class contains a private static inner class called IntegerCache that caches all Integer objects whose values lie between -128 and 127. When an Integer within this range is created, the JVM returns the cached instance instead of allocating a new object.

Example:

Integer a = 1000, b = 1000;
System.out.println(a == b); // false

Integer c = 100, d = 100;
System.out.println(c == d); // true

For the cached range, the code effectively becomes:

Integer c = Integer.valueOf(100);
Integer d = Integer.valueOf(100);

The implementation of Integer.valueOf() is roughly:

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

Thus, c == d evaluates to true because both references point to the same cached object, while a == b is false because 1000 lies outside the cache range and separate objects are created.

Why Does Integer Cache Exist?

The cache improves performance by avoiding repeated allocation of frequently used small integers, which appear often as loop counters, array indices, and other constants. Reusing the same objects reduces memory churn and speeds up execution.

Reflection API Trick

Using reflection, the IntegerCache can be altered at runtime, leading to surprising behavior. The following example modifies the cached value at index 132 (which corresponds to the integer 4) to point to the cached value for 5, causing the expression 2 + 2 to print 5:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Class<?> cacheClass = Integer.class.getDeclaredClasses()[0]; // IntegerCache class
    Field cacheField = cacheClass.getDeclaredField("cache"); // cache field
    cacheField.setAccessible(true);

    Integer[] newCache = (Integer[]) cacheField.get(cacheClass);
    newCache[132] = newCache[133]; // replace value 4 with 5

    int a = 2;
    int b = a + a;
    System.out.printf("%d + %d = %d", a, a, b); // prints: 2 + 2 = 5
}

This demonstration shows the power and danger of reflection: it can bypass normal safety checks and produce unpredictable results.

Conclusion

Understanding the IntegerCache and the reference semantics of == is essential for writing correct Java code. Developers should prefer equals() for value comparison of wrapper objects and use reflection cautiously, as it can easily break expected language behavior.

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.

JavaReflectionReference Equalityinteger
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

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.