Home >Java >javaTutorial >Why Does Java Cache Integers Only Between -128 and 127?
Why Integer Caching Values Between -128 and 127?
Regarding a previous question, it was established that the Integer class caches values between -128 and 127. This prompted the inquiry of why this specific range was chosen.
The Java Language Specification (JLS) mandates the caching for integers between -128 and 127. The rationale is to ensure that boxing of these values always yields identical references, guaranteeing indistinguishability for common cases. This promotes performance without imposing excessive memory overhead, especially on resource-constrained devices.
Frequent Request of Values Between -128 and 127
The choice of the range can be attributed to the assumption that integers in this interval are commonly used. While subjectivity exists, certain factors may support this assumption:
Caching Other Values Outside the Range
While the JLS mandates caching for the -128 to 127 range, the documentation suggests that other values may also be cached. This is configurable through the -XX:AutoBoxCacheMax JVM option. It allows developers to specify the maximum number of cached values outside the mandated range, providing flexibility for applications that require efficient boxing for a specific range of integers.
However, it's important to note that this option is implementation-specific and may not be available on all JVMs.
The above is the detailed content of Why Does Java Cache Integers Only Between -128 and 127?. For more information, please follow other related articles on the PHP Chinese website!