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"
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"
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!