Snehal Patel Snehal Patel - 11 months ago 54
Java Question

Comparing wrapper class with primitive using equals() gives strange behavior

Consider below code snap.
we use

to compare objects are meaningfully equivalent or not ?
Here both value are meaningfully equal but why does
And when I compared both value with
operator it returns

Long longWrapper = 0L;
long longPrimitive = 0;

System.out.println(longWrapper == 0L); // true
System.out.println(longWrapper == 0); //true
System.out.println(longWrapper == longPrimitive); //true

System.out.println(longWrapper.equals(0L)); //true
System.out.println(longWrapper.equals(0)); //false
System.out.println(longWrapper.equals(longPrimitive)); //true

Answer Source

longWrapper.equals(0) returns false, because 0 is autoboxed to Integer, not to Long. Since the two types are different, .equals() returns false.

In the meantime, longWrapper == 0 is true, because the longwrapper value is unboxed to 0, and 0 == 0 without considering the actual primitive types.