38
class datatype1
{

    public static void main(String args[])
    {
    int i1 = 1;
    Integer i2 = 1;
    Integer i3 = new Integer(1);

    System.out.println("i1 == i2"+(i1==i2));
    System.out.println("i1 == i3"+(i1==i3));
    System.out.println("i2 == i3"+(i2==i3));
}

}

Output

i1 == i2true
i1 == i3true
i2 == i3false

Can someone explain why I get false when comparing i2 and i3 ?

UnderDog
  • 3,173
  • 10
  • 32
  • 49

2 Answers2

74
i1 == i2

results in un-boxing and a regular int comparison is done. (see first point in JLS 5.6.2)

i2 == i3 

results in reference comparsion. Remember, i2 and i3 are two different objects. (see JLS 15.21.3)

Community
  • 1
  • 1
rocketboy
  • 9,573
  • 2
  • 34
  • 36
13
Integer i2 = 1;

This results is autoboxing. You are converting int(primitive type) to it's corresponding wrapper.

 Integer i3 = new Integer(1);

Here no need of autoboxing as you are directly creating an Integer object.

Now in

i1 == i2
i1 == i3

i2 and i3 are automatically unboxed and regular int comparison takes place which is why you get true.

Now consider

i2 == i3

Here both i2 and i3 are Integer objects that you are comparing. Since both are different object(since you have used new operator) it will obviously give false. Note == operator checks if two references point to same object or not. Infact .equals() method if not overridden does the same thing.

It is same as saying

    Integer i2 = new Integer(1);
    Integer i3 = new Integer(1);
    System.out.println("i2 == i3 "+(i2==i3));

which will again give you false.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • copy paste error your second code line is the same as the first – Marc-Andre Aug 26 '13 at 13:46
  • 3
    Well apologies for that but instead of down voting anyone could have edited it. – Aniket Thakur Aug 26 '13 at 14:44
  • I wasn't the downvoter, I was just saying was at first sight was wrong. And this was too minor for me to edit ! – Marc-Andre Aug 26 '13 at 14:45
  • 3
    "Infact .equals() method if not overridden does the same thing." Not sure what you mean here. If you test the last snippet of code with i2.equals(i3); it returns true. So I disagree that it does the same thing.... – Mark Nov 08 '17 at 18:04
  • I agree with Mark's assertion, I tested that line and .equals() returned true for me without any form of override. – austinkjensen Apr 18 '21 at 00:29
  • I think the point was that Object.equals() does reference comparison just like == operator. However Integer.equals() overrides that and does proper Integer comparison – Ilya Ivanov Jun 01 '21 at 10:12