Home >Java >javaTutorial >Why Does Integer Boxing in Java Sometimes Return `true` and Sometimes `false` for `==` Comparisons?

Why Does Integer Boxing in Java Sometimes Return `true` and Sometimes `false` for `==` Comparisons?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 00:50:14402browse

Why Does Integer Boxing in Java Sometimes Return `true` and Sometimes `false` for `==` Comparisons?

Understanding the Weirdness of Integer Boxing in Java

In Java, primitive data types like integers have corresponding wrapper classes, such as Integer, to provide object-oriented functionality. How these values are boxed and unboxed can lead to surprising results.

One such observation comes from the following code:

public class WeirdBoxing {
    public static void main(String[] args) {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);
        
        Integer c = 100, d = 100;
        System.out.println(c == d);
    }
}

When executed, this code prints:

false
true

Why does the first comparison return false while the second returns true? According to the == operator, references should always be compared.

The Mystery Behind the "True" Comparison

Interestingly, the true comparison is not a fluke. Java Language Specification (JLS) Section 5.1.7 states:

If the value p being boxed is [...] an int or short number between -128 and 127, [...] then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

In this instance, c and d both hold values within the specified range, causing their boxed representations (Integer objects) to be identical.

The Ambiguity of Non-Fixed-Range Comparisons

In contrast, the first comparison (a == b) does not fall under the guaranteed equality rule. The JLS emphasizes this:

For other values, [the rules] disallows any assumptions about the identity of the boxed values on the programmer's part.

Essentially, when boxing values outside the fixed range, there's no guarantee of identical references.

Conclusion

The strange behavior of Integer boxing in Java stems from the language specification's provision for efficiency and common use cases. While values within a certain range are guaranteed to be boxed identically, for other values, the identity of the boxed objects is unpredictable. This understanding illuminates the "weirdness" exemplified by the code snippet presented at the outset.

The above is the detailed content of Why Does Integer Boxing in Java Sometimes Return `true` and Sometimes `false` for `==` Comparisons?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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