2

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?

4
  • 1
    Because if x is null, then x.equals(y) will throw an exception.
    – khelwood
    Commented May 30, 2019 at 9:09
  • Because if that reference is null, then it would throw NullPointerException and that is the reason you need to check it with "==" or "!=" Commented May 30, 2019 at 9:11
  • can you try Objects.equals(o1, o2)?
    – dehasi
    Commented May 30, 2019 at 9:14
  • Objects.equals(x, y) is a helper method which first checks for null and then calls equals on the object.
    – MC Emperor
    Commented May 30, 2019 at 9:14

3 Answers 3

3

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.

1

There are three reasons in the following order of importance:

  1. 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.

  2. 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.

  3. 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).

0

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.