What is Objects.nonNull in Java?

Overview

The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not.

  • If the passed object is non-null, then the method returns true.
  • If the passed object is null, then the method returns false.

This method was introduced in Java 8. To use the nonNull method, import the following module.

java.util.Objects

Syntax

public static boolean nonNull(Object obj)

Parameters

This method takes one parameter, Object obj, an object reference to be checked against null.

Examples

In the code below, a non-null string object is passed to the nonNull method and returns true.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
String s = "hello";
System.out.println(Objects.nonNull(s));
}
}

In the code below, null is passed to the nonNull method and returns false.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
System.out.println(Objects.nonNull(null));
}
}