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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With