8

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?

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151

2 Answers2

11

As already pointed out in the comments, when doing

if(l1 == 2)

Long l1 gets automatically unboxed to its primitive type, long. So the comparison is between long and int.

In the second case, l1.longValue() will return the long value, as a primitive, of the Long represented by the Long object, so the comparison will be again between long and int. 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.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
-1

This behaviour is explained by widening and boxing.

In the first example,

if(l1 == 2)

what happens is as follows:

1: The compiler notices that you are comparing a wrapper (Long) with a primitive value (int), so it boxes the primitive, resulting in:

if (l1 == new Integer(2))

since 2 is an int (it lacks the 'L' at the end).

2: The compiler now notices that we are comparing a Long with an Integer, so it widens the Integer to a Long, resulting in:

if (l1 == new Long(new Integer(2))

3: Now we are comparing two Longs.

The other case is simpler, here the result is simply:

if (2L == 2)

comparing the primitive values, which is allowed even though they are different types.

Tobb
  • 11,850
  • 6
  • 52
  • 77
  • Not sure about your explanation about the first example. I think it's _unboxing_ of `l1` that's happening here, not _boxing_ of `2` into `Integer`. If it was that way, the only thing that could explain the `==` operator returning `true` would be caching, which wouldn't be a valid explanation if it was doing `new Integer(2)` anyway. Also, doing `new Long(123456) == 123456` returns `true`, and it seems to be a value out of the caching range. – Xavi López Feb 01 '13 at 10:12