Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the two Java operators: != vs !equals

Tags:

java

operators

Is this code:

elem1!=elem2

equivalent to this one?

!elem1.equals(elem2)

It compiles both ways, but I'm still unsure about it...

like image 802
bluehallu Avatar asked Dec 06 '22 21:12

bluehallu


1 Answers

== (and by extension !=) check for object identity, that is, if both of the objects refer to the very same instance. equals checks for a higher level concept of identity, usually whether the "values" of the objects are equal. What this means is up to whoever implemented equals on that particular object. Therefore they are not the same thing.

A common example where these two are not the same thing are strings, where two different instances might have the same content (the same string of characters), in which case a == comparison is false but equals returns true.

The default implementation of equals (on Object) uses == inside, so the results will be same for objects that do not override equals (excluding nulls, of course)

like image 182
Matti Virkkunen Avatar answered Dec 10 '22 13:12

Matti Virkkunen