Objects.requireNonNullElse()
Get a non-null value with a clear default, no ternary needed.
Code Comparison
โ Java 8
String name = input != null
? input
: "default";
// easy to get the order wrong
โ Java 9+
String name = Objects
.requireNonNullElse(
input, "default"
);
See a problem with this code? Let us know.
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()
Since JDK
9
Difficulty
Beginner
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