Why the Behavior of the Integer Constant Pool Differs After 127
The constant pool for numbers in Java differs from that of strings. While only compile-time constants are interned for strings, any boxing operation involves the pool for wrapper types of integers.
For instance:
int x = 10; int y = x + 1; Integer z = y; // Not a compile-time constant Integer constant = 11; System.out.println(z == constant); // true
The JLS guarantees a small range of pooled values, with implementations having the option to use a larger range.
In practice, most implementations use Integer.valueOf for boxing operations, leading to the following behavior:
Integer x = Integer.valueOf(100); Integer y = Integer.valueOf(100); System.out.println(x == y); // true
According to JLS section 5.1.7:
Values between -128 and 127 will always produce identical references when boxed. This is a practical compromise that ensures common values are always indistinguishable.
However, the behavior changes for values outside this range. For efficiency reasons, implementations may not assume shared references for these values.
This ensures desired behavior in most situations without significantly impacting performance. Memory-limited implementations can extend caching to cover a wider range of values.
The above is the detailed content of Why Do Integer Values Outside the Range -128 to 127 Behave Differently in Java's Constant Pool?. For more information, please follow other related articles on the PHP Chinese website!