Concept Explanation
NullPointerException is the most common exception in Java, and the reason is structural: a method returning User gives no hint about whether it might return nothing.
Optional<User> makes absence part of the type. The compiler now forces you to consider the empty case.
Creating One
Optional<String> present = Optional.of("value"); // throws if null
Optional<String> maybe = Optional.ofNullable(getName()); // null → empty
Optional<String> empty = Optional.empty();
Consuming One
Optional<User> found = repo.findByEmail(email);
// Default value
User user = found.orElse(User.guest());
// Lazily computed default — only runs when empty
User user = found.orElseGet(User::createGuest);
// Throw when absent
User user = found.orElseThrow(() -> new UserNotFoundException(email));
// Act only if present
found.ifPresent(u -> log.info("Found {}", u.getName()));
// Both branches
found.ifPresentOrElse(
u -> log.info("Found {}", u.getName()),
() -> log.warn("No user for {}", email));
Chaining
This is the real payoff. Compare the null-check version:
// The pyramid of doom
String city = null;
if (user != null) {
Address addr = user.getAddress();
if (addr != null) {
City c = addr.getCity();
if (c != null) city = c.getName();
}
}
with the Optional version:
String city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.map(City::getName)
.orElse("Unknown");
Any null along the chain short-circuits to empty. Four levels of nesting become one readable expression.
Use flatMap when the mapper itself returns an Optional:
Optional<String> nickname = findUser(id)
.flatMap(User::getNickname); // getNickname() returns Optional<String>
Filter inside the chain:
Optional<User> activeAdult = findUser(id)
.filter(User::isActive)
.filter(u -> u.getAge() >= 18);
Where Optional Belongs
| Use | Verdict |
|---|---|
| Return type of a lookup | ✅ exactly what it is for |
| Local variable in a chain | ✅ fine |
| Method parameter | ❌ overload the method instead |
| Field on an entity | ❌ not serialisable; use null |
| Collection element | ❌ use an empty collection |
For a missing collection, return List.of() — never Optional<List<T>>. An empty list already means "nothing".
Common Mistakes
optional.get()without checking: Reintroduces the exact crash you were avoiding. UseorElseThrowso the intent is explicit.if (opt.isPresent()) { opt.get() }: Technically safe but no better than a null check. UsemaporifPresent.orElsewith an expensive call:orElse(buildDefault())evaluatesbuildDefault()always, even when the value is present. UseorElseGet.- Returning
nullfrom a method typedOptional: A special kind of cruelty. ReturnOptional.empty(). Optionalfields in entities: Breaks JPA and Jackson. Keep it at the API boundary.
Best Practices
- Return
Optionalfrom any lookup that can legitimately find nothing. orElseGetfor computed defaults,orElsefor constants.- Never call
get()—orElseThrow()says the same thing and reads honestly. - Empty collections instead of
Optionalcollections.
Practice Exercises
- The Chain: Rewrite a three-level null check as an
Optionalchain ending inorElse. - The Eager Default: Prove
orElseevaluates its argument even when the value is present, by putting a print statement in the default factory. Then fix it withorElseGet. - The Repository: Change a finder returning
nullto returnOptional, and update all callers.