GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Optional chaining | java.evolved

Home / Errors / Optional chaining
Errors Beginner

Optional chaining

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Replace nested null checks with an Optional pipeline.

Optional Null Safety
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");
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🔗

Chainable

Each .map() step handles null transparently.

📖

Linear flow

Read left-to-right instead of nested if-blocks.

🛡️

NPE-proof

null 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
Optional ↗
Proof
View proof source ↗
Related patterns
Errors Beginner

Helpful NullPointerExceptions

Java 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!
Hover to see modern ➜
JDK 14+ →
Errors Beginner

Multi-catch exception handling

Pre-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);
}
Hover to see modern ➜
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"
    );
Hover to see modern ➜
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.