Problem:
Consider the following Java code:
Integer a = 1000, b = 1000; System.out.println(a == b); // false Integer c = 100, d = 100; System.out.println(c == d); // true
Why does the comparison of a and b return false while that of c and d returns true, despite both pairs having the same numerical values?
Answer:
To optimize memory and performance, the Java Virtual Machine (JVM) caches Integer instances within a specific range.
The JVM recognizes that small integer values (typically from -128 to 127) are used frequently in programs. Allocating a new Integer object for each such value would consume excessive memory. Therefore, the JVM maintains a cache of pre-allocated Integer instances within this range. When autoboxing occurs, or when literal integer values are assigned to Integer variables (e.g., Integer c = 100;), the JVM retrieves the corresponding instance from the cache.
This optimization significantly reduces memory overhead and improves cache efficiency. By storing multiple references to the same Integer object, the JVM can avoid the creation of redundant objects and optimize memory usage.
The above is the detailed content of Why Does Java's Integer Caching Affect `==` Comparisons?. For more information, please follow other related articles on the PHP Chinese website!