Read Also: not equal example in Java
1. Syntax:
public static boolean isNull(Object obj)
Returns true if the provided reference is null otherwise returns false.
2. Example:
import java.util.Objects; public class IsNullExample { public static void main(String args[]) { String str1 = null; String str2 = "JavaHungry"; System.out.println(Objects.isNull(str1)); //true System.out.println(Objects.isNull(str2)); //false } }
Output:
true
false
3. Difference between Objects.isNull() or obj == null
There is no difference between Objects.isNull() and obj == null. Internally, Objects.isNull() method is using obj==null check in the code as shown below:public static boolean isNull(Object obj) { return obj == null; }
4. When to use Objects.isNull() method over obj == null
1. Objects.isNull() can be easily used with Java 8 lambda expressions filtering.
For example:
It is much easier, easy to understand and cleaner to write:
.stream().filter(Objects::isNull)
than to write
.stream().filter(i -> i == null)
In the below code example, we have used the Objects.isNull() method instead of obj == null.
import java.util.List; import java.util.Objects; import java.util.stream.*; import java.util.Arrays; public class IsNullExampleTwo { public static void main(String args[]) { List<String> list = Arrays.asList("Alive", "is", null, "Awesome", null); List<String> result = list.stream().filter(Objects::isNull).collect(Collectors.toList()); System.out.println(result.size()); } }
Output:
2
2. You can make a typo as shown below if you are checking whether a boolean variable is null or not.
Boolean bool1 = false; if(bool1 = null) // Typo, we are using = instead of == { }
You can get rid of above typos by using Objects.isNull() method as shown below:
Boolean bool1 = false; if(Objects.isNull(bool1)) { }
That's all for today, please mention in the comments in case you have any questions related to Java isNull() method with examples.