What is Objects.requireNonNull in Java?
Overview
The requireNonNull method is a static method of the Objects class in Java. It checks whether the input object reference supplied to it is null.
- If the supplied object reference is
null, thenNullPointerExceptionis thrown. - If the object reference is not
null, then the reference is returned as it is.
This method was introduced in Java 8. To use the requireNonNull method, import the following module:
java.util.Objects
Method signature
public static <T> T requireNonNull(T obj)
Parameters
T obj: object reference.
Examples
In the code below, we pass a null reference to the method. When the program is run, it throws NullPointerException.
import java.util.Objects;public class Main {public static void main(String[] args) {Objects.requireNonNull(null);}}
In the following code, we pass a non-null reference to the method. When the program is run, it returns the passed reference.
import java.util.Objects;public class Main {public static void main(String[] args) {String s = "hello";System.out.println(Objects.requireNonNull(s));}}