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
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.
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.
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.
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.
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.
Its because 0 is not a long - its an int, and wrappers don't convert Integer's to Long's
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