Possible Duplicate:
Integer == int allowed in java
What is the difference between the following two statements
Long l1 = 2L;
if(l1 == 2)
System.out.println("EQUAL");
if(l1.longValue() == 2)
System.out.println("EQUAL");
They both are giving same result “EQUAL”.But my doubt is Long is object. How is it equal?
As already pointed out in the comments, when doing
Longl1gets automatically unboxed to its primitive type,long. So the comparison is betweenlongandint.In the second case,
l1.longValue()will return thelongvalue, as a primitive, of theLongrepresented by theLongobject, so the comparison will be again betweenlongandint. Answering your comment, take a look at What is the main difference between primitive type and wrapper class?The link given in the comments about autoboxing covers this subject quite well.