Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Objects.requireNonNull: checking references

In Java SE 21, `Objects.requireNonNull` returns the same reference if it is not `null`, or throws an exception. It checks that an argument is present, not that its contents are valid.

Version: Java SE 21

Syntax

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

// Method signatures in java.util.Objects (Java SE 21):
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)

Objects.requireNonNull is a generic static method in java.util.Objects. If obj is not null, the method returns that same reference as T, so you can use the result directly in an assignment. If obj is null, it does not return a fallback. It throws NullPointerException unless the supplier’s get() throws in the supplier overload, in which case that exception propagates instead.

The one-argument form takes no message. With the String overload, Java evaluates the message expression before the call, even if obj is not null. With Supplier<String>, Java still evaluates the supplier expression before the call, but the method calls get() to produce the message only if obj is null and the supplier is not null. The first two forms are available since Java 7 and the supplier form since Java 8. An uncast null literal as the second argument is ambiguous.

The Contact constructor rejects null separately for each of its three text arguments: firstName, lastName, and email. Empty strings still pass this check, and email format requires separate validation.

In tryAdvance, check action before testing whether the range is exhausted. With a valid action, no remaining element means false; if an element remains, the method passes it to the action and returns true when the action completes normally. A null action throws NullPointerException even after the range is exhausted.

Examples

import java.util.Objects;
import java.util.Spliterator;
import java.util.function.IntConsumer;

public class Main {
    record Contact(String firstName, String lastName, String email) {
        Contact {
            Objects.requireNonNull(firstName, "firstName");
            Objects.requireNonNull(lastName, "lastName");
            Objects.requireNonNull(email, "email");
        }
    }

    static final class Range implements Spliterator.OfInt {
        private int next = 7;
        private final int end = 8;

        @Override
        public boolean tryAdvance(IntConsumer action) {
            Objects.requireNonNull(action, "action");
            if (next >= end) {
                return false;
            }
            action.accept(next++);
            return true;
        }

        @Override public Spliterator.OfInt trySplit() { return null; }
        @Override public long estimateSize() { return end - next; }
        @Override public int characteristics() { return ORDERED | SIZED; }
    }

    public static void main(String[] args) {
        System.out.println(new Contact("Ada", "Lee", "not-an-email").email());
        try {
            new Contact("Ada", "Lee", null);
        } catch (NullPointerException ex) {
            System.out.println(ex.getClass().getSimpleName() + ": " + ex.getMessage());
        }

        Range range = new Range();
        IntConsumer print = System.out::println;
        System.out.println(range.tryAdvance(print));
        System.out.println(range.tryAdvance(print));
        try {
            range.tryAdvance((IntConsumer) null);
        } catch (NullPointerException ex) {
            System.out.println(ex.getClass().getSimpleName() + ": " + ex.getMessage());
        }
    }
}

Result

not-an-email
NullPointerException: email
7
true
false
NullPointerException: action

`not-an-email` passes the check, but a `null` email throws. The range passes `7` to the action, then returns `false` with a valid action, and still rejects `null` on the final call. The cast `(IntConsumer) null` selects the primitive overload.

Related lessons

  • Java · Lesson 8 · Advanced · Version: 2
  • Java · Lesson 23 · Advanced · Version: 2

Sources