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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
liv2hak
  • 14,472
  • 53
  • 157
  • 270

2 Answers2

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.

Steven Mastandrea
  • 2,752
  • 20
  • 26
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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • you mean '==' has been overridden in this case to compare the integer values instead of the address of the objects? – liv2hak Oct 06 '13 at 05:00
  • 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. – Steven Mastandrea Oct 06 '13 at 05:05
  • 1
    @liv2hak No not at all the concept of `==`. It's concept of caching and improving language performance. – Suresh Atta Oct 06 '13 at 05:13