Home > Java > javaTutorial > Why Does Java's `==` Operator Sometimes Compare Integer Object Values and Sometimes References?

Why Does Java's `==` Operator Sometimes Compare Integer Object Values and Sometimes References?

Barbara Streisand
Release: 2024-12-24 02:28:14
Original
185 people have browsed it

Why Does Java's `==` Operator Sometimes Compare Integer Object Values and Sometimes References?

Surprising Integer Boxing Behavior in Java

In Java, an Integer object is a wrapper for a primitive int value. When boxing an int into an Integer, one would typically expect the == operator to compare the values of the objects. However, in certain cases, the == operator instead compares the references of the objects. This behavior can lead to surprising results.

Consider the following code:

public class Scratch {
    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);
    }
}
Copy after login

When run, this code prints:

false
true
Copy after login

The first output is as expected: == compares the references of two distinct Integer objects. However, the second output is surprising. Why does == return true when c and d have the same value?

The answer lies in the Java Language Specification (JLS). According to Section 5.1.7 of the JLS:

If the value p being boxed is true, false, a byte, a char in the range u0000 to u007f, or 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.

This means that Integer objects created from primitive values within the specified ranges are guaranteed to have identical references. In our case, c and d are both created from the same int value, 100, which falls within the range of -128 to 127. Therefore, they have the same reference, and the == operator returns true.

While the behavior of the second line of output is guaranteed, the JLS suggests that the behavior of the first line of output is not. In theory, a Java implementation could cache Integer objects for common values to improve performance, but the JLS does not require this behavior. As a result, different Java implementations may handle this case differently.

The above is the detailed content of Why Does Java's `==` Operator Sometimes Compare Integer Object Values and Sometimes References?. 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