liveBook · Manning

Objects.requireNonNull

As explained in 100 Java Mistakes and How to Avoid Them

Objects.requireNonNull is a Java utility method that returns a non-null reference or throws NullPointerException when its argument is null.

Objects.requireNonNull returns its reference argument when non-null and throws NullPointerException when null. Use it at public method and constructor entry points to reject invalid input early, optionally supplying a clarifying message. section 5.1.1

public class Person {
  private final String firstName, lastName;

  public Person(String firstName, String lastName) {
    this.firstName = Objects.requireNonNull(firstName);
    this.lastName = Objects.requireNonNull(lastName);
  }
}

Initialize fields through requireNonNull so construction cannot silently store null values. section 5.1.1

Apply the pattern deliberately:

  • Validate each reference parameter immediately, especially in public methods and constructors. section 5.1.1
  • Use the returned reference when assigning fields, preventing delayed failures caused by an accidentally stored null. section 5.1.1
  • For collections, traverse elements with requireNonNull when necessary; consider List.copyOf, Set.copyOf, or Map.copyOf when copying and rejecting nulls is acceptable. section 5.1.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines return-or-throw behavior, optional messages, field initialization, and collection checks, while noting collection-validation cost.
Examples
Uses constructor field assignments and collection element traversal as focused validation examples.
What it assumes
Assumes familiarity with Java references, constructors, parameters, and NullPointerException while teaching explicit null validation.
What you can do after
Apply it via Objects.requireNonNull to fail early and preserve valid object state.
How it connects
Connects null handling with NullPointerException, defensive programming, field invariants, and collection factory methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.