java.util.Objects.isNull vs object == null

As you know, java.util.Objects is

This class consists of static utility methods for operating on objects.

One of such methods is Objects.isNull().

My understanding is that Objects.isNull() would remove the chance of accidentally assigning a null value to object by omitting the second =.

However, the API Note states:

This method exists to be used as a Predicate, filter(Objects::isNull)

Would there be any reason/circumstance for which I should use object == null over Objects.isNull() in an if statement?

Should Objects.isNull() be confined to Predicates exclusively?


Solution 1:

should use object == null over Objects.isNull() in a if statement?

If you look at the source code of IsNull method,

 /* Returns true if the provided reference is null otherwise returns false.*/

 public static boolean isNull(Object obj) {
     return obj == null;
 }

It is the same. There is no difference. So you can use it safely.

Solution 2:

Objects.isNull is intended for use within Java 8 lambda filtering.

It's much easier and clearer to write:

.stream().filter(Objects::isNull) 

than to write:

.stream().filter(x -> x == null).  

Within an if statement, however, either will work. The use of == null is probably easier to read but in the end it will boil down to a style preference.

Solution 3:

Look at the source:

public static boolean isNull(Object obj) {
    return obj == null;
}

To check for null values, you can use:

  • Objects.isNull(myObject)
  • null == myObject // avoids assigning by typo
  • myObject == null // risk of typo

The fact that Objects.isNull is meant for Predicates does not prevent you from using it as above.