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
