Home > Java > javaTutorial > Why are Java\'s Integer Wrapper Objects Shared Only Between -128 and 127?

Why are Java\'s Integer Wrapper Objects Shared Only Between -128 and 127?

Mary-Kate Olsen
Release: 2024-11-26 14:54:09
Original
574 people have browsed it

Why are Java's Integer Wrapper Objects Shared Only Between -128 and 127?

Integer Wrapper Objects: Shared Instances Within the Range of -128 to 127

Java's wrapper objects provide a crucial bridge between primitive data types and objects. However, a peculiar behavior has been observed in the boxing of integer values: instances appear to be shared only within the range of -128 to 127.

Consider the following code:

Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2);  // outputs "true"
Copy after login

In this case, integer1 and integer2 are assigned the same instance, as evidenced by the output of "true" when comparing them with ==. However, a different behavior is exhibited when the values exceed this range:

Integer integer1 = 128;
Integer integer2 = 128;
System.out.println(integer1 == integer2);  // outputs "false"
Copy after login

Why does this phenomenon occur?

According to the Java Language Specification (JLS), it is specifically stated that "certain common values always be boxed into indistinguishable objects." This range is defined as "a byte, or a char in the range u0000 to u007f, or an int or short number between -128 and 127 (inclusive)".

The justification for this behavior, as explained in the JLS, is to "ensure that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices." By restricting the shared instance behavior to a common value range, Java strikes a balance between performance and the expected behavior.

The above is the detailed content of Why are Java\'s Integer Wrapper Objects Shared 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