Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 385
Snehal Patel Avatar asked Feb 20 '15 07:02

Snehal Patel


People also ask

What is the difference between wrapper class and primitive?

The difference between wrapper class and primitive type in Java is that wrapper class is used to convert a primitive type to an object and object back to a primitive type while a primitive type is a predefined data type provided by the Java programming language.

Can we compare wrapper classes using == in Java?

When a wrapper is compared with a primitive using ==, the wrapper is unwrapped. That's true! But which method is invoked/called depends on the type of the wrapper. If your wrapper is of type Integer, then indeed the intValue method will be called.

How can the values of wrapper class objects be compared?

Comparing Integers Integer is a wrapper class of int, and it provides several methods and variables you can use in your code to work with integer variables. One of the methods is the compareTo() method. It is used to compare two integer values. It will return a -1, 0, or 1, depending on the result of the comparison.

What is the difference between equals () and == when comparing objects in Java?

In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.


2 Answers

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.

like image 78
Konstantin Yovkov Avatar answered Oct 02 '22 21:10

Konstantin Yovkov


Its because 0 is not a long - its an int, and wrappers don't convert Integer's to Long's

like image 30
farrellmr Avatar answered Oct 02 '22 22:10

farrellmr