Optional: Avoiding NullPointerException
Optional is a container that may or may not hold a value, designed as a return type that makes "no result" explicit. Interviewers check that you use it well: no get() without a check, and no Optional fields or parameters.
What you will learn
- Create Optionals with of, ofNullable and empty
- Use map, flatMap, filter, orElse, orElseGet and orElseThrow
- Know the difference between orElse and orElseGet
- Know where not to use Optional
Key concepts
Purpose
A method return type for "maybe a value", such as Spring Data findById. It forces the caller to handle absence.
orElse vs orElseGet
orElse(x) always evaluates x, even when a value is present. orElseGet(() -> x) calls the supplier only when empty. Use orElseGet for expensive defaults.
Anti-patterns
Optional fields (not Serializable, adds overhead), Optional parameters, Optional of collections (return an empty list), and opt.get() without isPresent.
Step by step
Typical service code
public UserDto getUser(long id) {
return userRepository.findById(id)
.filter(User::isActive)
.map(UserDto::from)
.orElseThrow(() -> new UserNotFoundException(id));
}
String city = user.flatMap(User::address).map(Address::city).orElse("Unknown");Examples
orElse evaluates eagerly
Optional<String> name = Optional.of("Sumit");
name.orElse(loadDefaultFromDb()); // loadDefaultFromDb() still runs!
name.orElseGet(() -> loadDefaultFromDb()); // does not runPractise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Refactor nested null checks (user → address → city) into an Optional chain.
- Explain why Optional<List<T>> is a smell.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Optional.of vs ofNullable?
Optional.of(x) throws NullPointerException if x is null, so use it when null would be a bug. ofNullable(x) returns an empty Optional for null.
Summary
Use Optional as a return type for maybe-absent results, chain map/filter/orElseThrow, prefer orElseGet for costly defaults, and never use it for fields, parameters or collections.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus