Why Does Integer.valueOf(100) Return the Same Object? Unveiling Java’s Integer Cache
Running simple Integer comparisons in Java reveals that values between -128 and 127 are cached, making identical literals share the same object, while larger numbers are distinct, and the article explains the underlying IntegerCache mechanism, its source code, and how reflection can alter it.
This article discusses an interesting Java behavior when comparing Integer objects.
Running the following code:
Integer a = 1000, b = 1000;
System.out.println(a == b); // false
Integer c = 100, d = 100;
System.out.println(c == d); // trueIt demonstrates that a == b is false while c == d is true.
Fundamentally, the == operator checks whether two references point to the same object, not whether their values are equal.
Java’s Integer class contains a private inner class IntegerCache that caches Integer objects for values from -128 to 127. When a literal within this range is assigned, the JVM actually calls Integer.valueOf(), which returns a cached instance.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}Therefore, two variables such as c and d that hold the value 100 reference the same cached object, making c == d evaluate to true.
The cache improves performance and reduces memory usage because small integers are used far more frequently than large ones.
Using reflection, the cache can be accessed and modified, as shown in the following example:
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
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);
}This code demonstrates how the internal cache can be altered, which may affect subsequent Integer comparisons.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
