Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Objects.requireNonNull — reference checks and error messages

Check a required parameter: `Objects.requireNonNull` returns the same reference if it isn't `null` and normally throws `NullPointerException` if it is. You can supply a custom message.

Version: Java SE 21

Syntax

import java.util.Objects;
import java.util.function.Supplier;

// Java SE 21: static method signatures in java.util.Objects
public static <T> T requireNonNull(T obj)
public static <T> T requireNonNull(T obj, String message)
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)

In Java SE 21, Objects.requireNonNull is a static generic method in java.util.Objects. Import java.util.Objects to use the short class name Objects. If obj is not null, the method returns exactly the same reference as T, without copying the object. If obj is null, it throws NullPointerException instead of returning a value, unless a message supplier itself throws.

Use it at the start of a method or constructor to reject null immediately for a required parameter. Objects.requireNonNull(obj) doesn't accept a custom message. In Objects.requireNonNull(obj, "name must not be null"), the second argument is a String used as the exception's detail message, not a fallback value. The String argument expression is evaluated before the call, even when obj is not null.

If building the message is expensive, you can pass a Supplier<String> from java.util.function, as in Objects.requireNonNull(obj, () -> buildMessage()). The lambda body runs only if obj is null. If the supplier throws an unchecked exception or an Error, that throwable propagates unchanged instead of requireNonNull throwing its own NullPointerException. Objects.requireNonNull(obj, null) doesn't compile because null matches both String and Supplier<String>. Use the one-argument overload if you don't need a custom message.

The method checks only whether the reference is null: an empty string passes. To replace null instead of rejecting it, use Objects.requireNonNullElse with a non-null fallback.

Examples

import java.util.Objects;

public class Main {
    private final String name;

    public Main(String name) {
        this.name = Objects.requireNonNull(name, "name must not be null");
    }

    public static void main(String[] args) {
        String name = "Ada";
        Main entry = new Main(name);
        System.out.println(entry.name == name);

        try {
            new Main(null);
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}

Result

true
name must not be null

The first line is `true` because `==` compares references and the field holds the same reference passed to the constructor. On the second call, the constructor throws; the `catch` block prints only the detail message from `getMessage()`.

Related lessons

  • Java · Lesson 28 · Intermediate · Version: 2

Sources