Objects.requireNonNullElse()
Home / Errors / Objects.requireNonNullElse()
Code Comparison
String name = input != null
? input
: "default";
// easy to get the order wrong
String name = Objects
.requireNonNullElse(
input, "default"
);
Why the modern way wins
๐
Clear intent
Method name describes exactly what it does.
๐ก๏ธ
Null-safe default
The default value is also checked for null.
๐
Readable
Better than ternary for simple null-or-default logic.
Old Approach
Ternary Null Check
Modern Approach
requireNonNullElse()
JDK Support
Objects.requireNonNullElse()
Available
Widely available since JDK 9 (Sept 2017)
How it works
requireNonNullElse returns the first argument if non-null, otherwise the second. The default itself cannot be null โ it throws NPE if both are null, catching bugs early.
Related Documentation
Proof