Lesson 20: Optional & Avoiding NullPointerException
21 Jul 2026 1 min Swarnil Singhai
Optional makes 'this might not have a value' explicit in the type system, forcing callers to handle the absence instead of risking an NPE.
Real-time example
A user-lookup service returns Optional<User> so callers can't forget to handle 'user not found' — the compiler nudges them.
Optional<User> findUser(String id) {
return id.equals("u1") ? Optional.of(new User("Amit")) : Optional.empty();
}
findUser("u2")
.map(u -> u.name)
.ifPresentOrElse(
name -> System.out.println("Found: " + name),
() -> System.out.println("No such user")
);
What's happening
ifPresentOrElse forces you to handle both branches at the call site instead of silently returning null and crashing later.
Never call .get() on an Optional without checking isPresent() first — that defeats the entire point.
Advertisement