The null
literal can only be assigned to reference variables, and usually, we use the .equals()
method in comparing with them
Why do we use the operators "equal to" and "not equal to" instead of the .equals()
method if dealing with null?
equals
is a method, meaning you cannot call it on a null
reference (although you could call myVariable.equals(aVariableThatIsNull)
, and it should return false
).
You could use java.util.Objects#equals(Object, Object)
to clean up your code, and seemless handle null-safe equality checks.
There are three reasons in the following order of importance:
Stability - The fear of NullPointerException
which would most certainly happen if you tried to access equals()
method from a object that holds a null
value. This is pretty obvious but still had to be mentioned as the primary reason.
Visibility - However even if we could do that and it wouldn't throw an exception it would still not be more preferable to using the ==
operator. Why? Because the operator visually separates the elements making it more clear what is actually being compared. When we are comparing to a null
we want it to be clear and visible within the code.
Consistency - Equals method is used for content comparison while the ==
operator is used for address comparison. Since null has no address because it doesn't exist the most logically consistent thing would be to first compare the lack of address before moving on to compare the actual content of two objects (which is what equals()
does).
Method "equals()" is an instance method, and to call any instance method , you need a non null object reference. So calling equals() with null reference will result in NPE.
If the method is static, then you can invoke that method with null reference too as static method is not bound to any instance.
x
is null, thenx.equals(y)
will throw an exception.Objects.equals(o1, o2)
?Objects.equals(x, y)
is a helper method which first checks for null and then callsequals
on the object.