3
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?

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3
x == y

is true for values between -128 and 127 due to integer caching.

Try

 Integer x = 130;
 Integer y = 140;

Now compare and see the magic.

From language spec

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.

Reason:

The behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might.

3 Comments

you mean '==' has been overridden in this case to compare the integer values instead of the address of the objects?
It's not that '==' has been overridden to compare the values, it's that in all cases where you're creating a new Integer(1) Object, there exists only 1 Object and the internals return that Object reference rather than creating a new one.
@liv2hak No not at all the concept of ==. It's concept of caching and improving language performance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.