Java isNull method

In this post, we will about Objects class’s isNull method.

Objects’s isNull() method is used to check if object is null or not. java.util.Objects class was introduced in java 7.

Here is simple example for Object's isNull method.

package org.arpit.java2blog;

import java.util.Objects;

public class ObjectsIsNullMain {

    public static void main(String[] args) {
        String str1="Java2blog";
        String str2=null;

        System.out.println("Is str1 null: "+Objects.isNull(str1));
        System.out.println("Is str2 null: "+Objects.isNull(str2));
    }
}

Output:

Is str1 null: false
Is str2 null: true

Let’s look at source code Object’s isNull() method.

 /**
     * Returns {@code true} if the provided reference is {@code null} otherwise
     * returns {@code false}.
     *
     * @apiNote This method exists to be used as a
     * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
     *
     * @param obj a reference to be checked against {@code null}
     * @return {@code true} if the provided reference is {@code null} otherwise
     * {@code false}
     *
     * @see java.util.function.Predicate
     * @since 1.8
     */
    public static boolean isNull(Object obj) {
        return obj == null;
    }

As you can see, it just checks if obj is null or not.

Advantage of isNull over obj==null

  1. In case, you are checking if boolean variable is null or not. You can make typo as below.

      Boolean boolVar=true;     
        if(boolVar = null)  // typo
        {
    
        }
    

    You can use isNull() method to avoid this kind of typos.

      Boolean boolVar=true;     
        if(Objects.isNull(boolVar))  // typo
        {
    
        }
    
  2. Object’s isNull() method can be used with Java 8 lambda expressions.

It is cleaner and easier to write.

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

than to write:

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

That’s all about isNull method in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.