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 — Optional chaining | java.evolved
Errors
Beginner
Optional chainingReplace nested null checks with an Optional pipeline. Code Comparison
✕ Java 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");
See a problem with this code? Let us know.
Why the modern way wins
🔗
ChainableEach .map() step handles null transparently. 📖
Linear flowRead left-to-right instead of nested if-blocks. 🛡️
NPE-proofnull is handled at each step — no crash possible. Old Approach
Nested Null Checks
Modern Approach
Optional Pipeline
Since JDK
9
Difficulty
Beginner
JDK Support
Optional chaining
Available
Available since JDK 8+ (improved in 9+) How it works
Optional.map() chains through nullable values, short-circuiting on the first null. orElse() provides the default. This eliminates pyramid-of-doom null checking. 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
Beginner
Multi-catch exception handlingPre-Java 7
try {
process();
} catch (IOException e) {
log(e);
} catch (SQLException e) {
log(e);
} catch (ParseException e) {
log(e);
}
Java 7+
try {
process();
} catch (IOException
| SQLException
| ParseException e) {
log(e);
}
JDK 7+
→
Errors
Beginner
Objects.requireNonNullElse()Java 8
String name = input != null
? input
: "default";
// easy to get the order wrong
Java 9+
String name = Objects
.requireNonNullElse(
input, "default"
);
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. |