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"
);
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.