Integer Wrapper Objects Share Instances Within the Range -128 to 127
The behavior of integer wrapper objects sharing instances within a specific value range arises from the Java Language Specification (JLS). According to JLS 5.1.7, boxing conversions for certain primitive values yield identical references:
For true, false, byte, char (range u0000 to u007f), and int or short numbers between -128 and 127, the wrapper objects created from these values will always be the same.
This specification allows for pragmatic efficiency while ensuring desired behavior in typical scenarios. The caching of certain common values as objects helps reduce memory overhead during boxing conversions. However, the implementation can decide whether to cache all or only a subset of the specified values, ranging from -32K to 32K for char and short values, and int and long values.
Therefore, integer wrapper objects share the same instances only within the value range of -128 to 127 because it is dictated by the specifications of the Java language, aiming to balance memory efficiency and predictability in value conversions.
The above is the detailed content of Why Do Integer Wrapper Objects in Java Share Instances Only Between -128 and 127?. For more information, please follow other related articles on the PHP Chinese website!