Objects.requireNonNull()
Checks that a value is not null and throws NullPointerException with a clear message right away.
Available since: Java 7
Syntax
static <T> T requireNonNull(T obj, String message)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | T | The value to check. |
| message | String | The error text. Optional. |
Return value
TThe same value if it is not null — so the call fits right into an assignment.
Examples
Checking an argument in a constructor:
class User {
final String name;
User(String name) {
this.name = Objects.requireNonNull(name, "name must not be null");
}
}
void main() {
IO.println(new User("Anna").name);
try {
new User(null);
} catch (NullPointerException e) {
IO.println(e.getMessage());
}
}Output:
Anna
name must not be nullA default instead of null — requireNonNullElse() (Java 9):
void main() {
String nickname = null;
IO.println(Objects.requireNonNullElse(nickname, "guest"));
}Output:
guestNotes
The error appears right when the object is created rather than later, when the null blows up somewhere else — which makes the cause easier to find.
See also
- Objects.isNull() — Checks whether a value is null; its partner nonNull() does the opposite.
- throw — Throws an exception and stops the method.
Related recipes
In the tutorial
- Encapsulation — Encapsulation in Java: the private modifier, getters and setters, data validation and final fields.