Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int vs Integer comparison Java [duplicate]

Tags:

java

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 ?

like image 321
UnderDog Avatar asked Aug 26 '13 13:08

UnderDog


People also ask

Can you compare integer and int in Java?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it.

Can you compare doubles to ints in Java?

Double compare() Method in Java with ExamplesThe compare() method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.

Can int and double be compared?

All int s are exactly representable as double .

Can we compare two integers in Java?

Java Integer compare() methodpublic static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.


2 Answers

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)

like image 126
rocketboy Avatar answered Oct 09 '22 13:10

rocketboy


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.

like image 26
Aniket Thakur Avatar answered Oct 09 '22 11:10

Aniket Thakur