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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
/** * 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
-
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 { } |
-
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.
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.