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

Snehal Patel picture Snehal Patel · Feb 20, 2015 · Viewed 8.5k times · Source

Consider below code snap. we use equals() to compare objects are meaningfully equivalent or not ? Here both value are meaningfully equal but why does longWrapper.equals(0) return false ? And when I compared both value with == operator it returns true.

    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

Konstantin Yovkov picture Konstantin Yovkov · Feb 20, 2015

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.