Java Integer Caching
The Ghost in the Machine: Understanding Java Integer Caching
In Java, 100 == 100 is TRUE… but 200 == 200 is FALSE? 🤯
Sounds like a language glitch, right? It’s actually a feature introduced way back in 2004 with Java 5. Here is why it happens and why it breaks code in production:
Step 1: The Unexpected Behavior (== with Integer Objects)
When you assign numbers to Integer object wrappers and compare them using ==:
// Comparing values within the cache range (-128 to 127)
Integer num1 = 100;
Integer num2 = 100;
System.out.println(num1 == num2); // Output: true
// Comparing values outside the cache range
Integer num3 = 200;
Integer num4 = 200;
System.out.println(num3 == num4); // Output: false
Why it happens: The == operator compares memory references (addresses) of objects rather than their internal numeric values.
Step 2: What Java Does Behind the Scenes (Autoboxing)
When you write Integer num = 100; Java automatically converts primitive int values into Integer objects via autoboxing:
// What you write:
Integer num1 = 100;
Get Md. Zahid Fesabelilla’s stories in your inbox
Join Medium for free to get updates from this writer.
// What Java compiles behind the scenes:
Integer num1 = Integer.valueOf(100);
Inside the JDK library, the Integer.valueOf() method checks if the number is cached:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) // Range: -128 to 127
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Why 100 == 100 is true: The JVM creates and caches Integer objects for numbers from -128 to 127 at startup. For 100, both variables point to the exact same cached memory address.
Why 200 == 200 is false: 200 falls outside the cached range, so Java allocates two separate objects with different memory addresses
Step 3: The Proper Solution (Using .equals())
To compare the actual numeric values inside object wrappers, use .equals():
Integer num3 = 200;
Integer num4 = 200;
// Compares underlying values instead of memory references System.out.println(num3.equals(num4)); // Output: true
Rule: .equals() unpacks the values and checks if they match, returning true regardless of cache range
#Java #JavaProgramming #BackendDevelopment #SoftwareEngineering #CleanCode #JavaDeveloper #CodingBugs #JVM #ComputerScience #TechCommunity










