Home > Java > javaTutorial > body text

Why Do Integer Wrapper Objects in Java Share Instances Only Between -128 and 127?

Patricia Arquette
Release: 2024-11-27 21:08:10
Original
854 people have browsed it

Why Do Integer Wrapper Objects in Java Share Instances Only Between -128 and 127?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template