Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: class Integer == operator strange behaviour [duplicate]

Tags:

java

eclipse

public class IntegerVsInt {

    public static void main(String args[])
    {
        int a = 1;
        int b = 1;
        int c = a + b;

        System.out.println(c);
        System.out.println(a == b);

        Integer x = 1;
        Integer y = 1;
        Integer z = x + y;

        System.out.println(z);
        System.out.println(x == y);
    }
}

In the above code I am comparing two int's and two objects of type integer.

When you compare two int's

a == b

I would expect their values to be compared.

However when you compare two Integer's

x == y

I would expect the address of the two object to be compared and then return a false.

I get true in both the cases? Why is this behavior?

like image 230
liv2hak Avatar asked Jul 13 '26 21:07

liv2hak


1 Answers

The == is testing whether the Integers are the same object. In java, certain small values are required to be cached, as well as others may optionally be cached, which is why the == Object reference evaluates to true.

The snippet from the JLS Spec 5.1.7

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

like image 191
Steven Mastandrea Avatar answered Jul 16 '26 13:07

Steven Mastandrea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!