Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare Long value in java [duplicate]

Tags:

java

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?

like image 624
PSR Avatar asked Feb 01 '13 08:02

PSR


People also ask

How do you compare two long values in Java?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object. It returns false if both the objects are not same.

Can we compare double and long in Java?

The main difference between long and double in Java is that long is a data type that stores 64 bit two's complement integer while double is a data type that stores double prevision 64 bit IEEE 754 floating point. In brief, long is an integral type whereas double is a floating point type.

Can you compare long int?

Yes, that's fine. The int will be implicitly converted to a long , which can always be done without any loss of information. Save this answer.


1 Answers

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.

like image 197
Xavi López Avatar answered Oct 05 '22 14:10

Xavi López