GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Objects.requireNonNullElse() | java.evolved
Errors
Beginner
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 intentMethod name describes exactly what it does. 🛡️
Null-safe defaultThe default value is also checked for null. 📏
ReadableBetter 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
Related patterns
Errors
Beginner
Helpful NullPointerExceptionsJava 8
// Old NPE message: // "NullPointerException" // at MyApp.main(MyApp.java:42) // Which variable was null?! Java 14+
// Modern NPE message: // Cannot invoke "String.length()" // because "user.address().city()" // is null // Exact variable identified!
JDK 14+
→
Errors
Intermediate
Record-based error responsesJava 8
// Verbose error class
public class ErrorResponse {
private final int code;
private final String message;
// constructor, getters, equals,
// hashCode, toString...
}
Java 16+
public record ApiError(
int code,
String message,
Instant timestamp
) {
public ApiError(int code, String msg) {
this(code, msg, Instant.now());
}
}
JDK 16+
→
Errors
Beginner
Optional chainingJava 8
String city = null;
if (user != null) {
Address addr = user.getAddress();
if (addr != null) {
city = addr.getCity();
}
}
if (city == null) city = "Unknown";
Java 9+
String city = Optional.ofNullable(user)
.map(User::address)
.map(Address::city)
.orElse("Unknown");
JDK 9+
→
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |