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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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 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.
1234567Boolean boolVar=true;if(boolVar = null) // typo{}You can use
isNull()
method to avoid this kind of typos.1234567Boolean 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.
1 2 3 |
.stream().filter(Objects::isNull) |
than to write:
1 2 3 |
.stream().filter(a -> a == null). |
That’s all about isNull method in java.