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
.
null
, then NullPointerException
is thrown.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
public static <T> T requireNonNull(T obj)
T obj
: object reference.
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));}}