Lesson · Optional
Optional: a value that may be missing
12 min readOptional
Nulls fail silently and far from their cause. Optional moves the possibility of absence into the type, so the compiler makes every caller confront the empty case before they can reach the value.
The bill for a null
A method returning String can mean a value or nothing, and its signature cannot say which. Callers forget one branch, and the null travels until something far away trips over it: a NullPointerException at a line that has nothing to do with the mistake.
The deeper cost is not the crash, it is the uncertainty. Every return value is suspect, so defensive null checks multiply, and the ones that matter get buried among the ones that never fire.
String name = lookup("ada"); // may be null: the signature refuses to say name.length(); // NPE here, cause elsewhere
What Optional is, and is not
Optional<T> is a small container holding either one T or nothing. It is a return-type tool: an API that may produce no value returns Optional and its callers get absence in the type system. Java 8 added it precisely because signatures could not express 'may be missing'.
It is not a replacement for null everywhere. Fields, method parameters and collection elements should not be Optional: a field that may be absent is nullable internal state, and an Optional parameter forces every caller to wrap something for no gain. The value of Optional is at the boundary where a method answers a question that may have no answer.
| Factory | Use for | Example |
|---|---|---|
| Optional.of(v) | a value that must be there | Optional.of("jvm") |
| Optional.ofNullable(v) | a value that may be null | Optional.ofNullable(map.get(k)) |
| Optional.empty() | an absent result | return Optional.empty(); |
| Optional.of(v).orElseThrow() | fail fast on a value that must exist | unwrap with an exception, not get() |
The chain that never NPEs
The real payoff is chaining. map applies the function only when a value is present and produces an empty Optional otherwise; if the mapper itself returns null, the result is empty as well. filter keeps the value only when the predicate passes, and flatMap handles mappers that return an Optional themselves.
A chain of map and filter reads like a pipeline with absence handled by construction. There is no branch and no null check, because empty propagates.
Optional<Player> player = findPlayer("grace"); String label = player .map(Player::name) // runs only when present .filter(n -> !n.isBlank()) .orElse("unknown");
orElse, orElseGet and the eager trap
orElse takes an already-computed fallback, so the fallback expression is evaluated whether or not it is used. orElseGet takes a supplier and calls it only when the Optional is empty. For a constant that difference is nothing; for an object, a query or a log line, it is the whole point.
orElseThrow turns absence into an exception at the point where the absence is a genuine error. It replaces both the get() call and the manual isPresent check, and it fails with a message you choose instead of a bare NoSuchElementException.
String a = opt.orElse(expensiveDefault()); // expensiveDefault() runs even when opt has a value String b = opt.orElseGet(() -> expensiveDefault()); // supplier runs only when empty String c = opt.orElseThrow(() -> new IllegalStateException("config missing"));
The eager evaluation of orElse is the single most common Optional bug in review. If the fallback is more than a literal, orElseGet is almost always the right call.
Optional lane · absence propagates, nothing throws
pick a lookuplookup: value present
supplier never called: the value was already there.
ifPresent and the isPresent anti-pattern
isPresent followed by get is the classic trap: it is a null check with extra steps, and it throws away everything Optional offers. ifPresent runs a consumer when a value exists; ifPresentOrElse (Java 9) handles both branches without unwrapping; stream() lets the value join a pipeline, mapping empty to zero elements.
opt.ifPresent(System.out::println); opt.ifPresentOrElse( name -> System.out.println("found: " + name), () -> System.out.println("not found")); findPlayer("ada").stream().map(Player::name).forEach(System.out::println); // zero or one element
Rules that keep Optional useful
Optional is a tool with a narrow, well-earned place. These rules come from its own designers and from a decade of reviews:
- Return values only. Fields use nullable state plus an accessor; parameters rarely need it; collections replace it (an empty list beats an empty Optional).
- Never Optional<Optional<T>>. flatMap exists to collapse the nesting; reaching the double layer means a mapper already returns Optional.
- get() before an isPresent check is an anti-pattern. Prefer orElse, orElseThrow, ifPresent, ifPresentOrElse or the stream bridge.
- Keep chains one screen long. An Optional chain that spans twenty lines is a control flow rewrite waiting to happen.
- No Serialization. Optional is deliberately not Serializable; it belongs at method boundaries, not in persisted state.
Absence in the type, not in the hope
The purpose is not fewer nulls in your code; it is fewer unknowns in your API. When a method can produce nothing, say so in its return type and let every caller find out at compile time instead of at 3 a.m.
Interview angles
Why was Optional introduced, and what problem does it actually solve?+
Signatures could not express that a method may return nothing. Optional makes absence explicit in the type system and enables chains (map, filter, orElse) that propagate emptiness without null checks.
orElse versus orElseGet?+
orElse evaluates its argument eagerly, every call, even when the Optional has a value. orElseGet takes a Supplier and only invokes it on empty. Beyond literals, orElseGet is almost always correct.
Should Optional be used for fields or parameters?+
No. It was designed for return values. Fields are better as nullable internals behind accessors, parameters just add wrapping ceremony, and Optional is not Serializable, which breaks persisted or remoted state.
What happens when the mapping function returns null inside map?+
map treats a null result as absence: the returned Optional is empty. There is no way (and no need) to wrap a null; use flatMap when the mapper itself returns an Optional.
Common misconception: Some assume map wraps the null into Optional.of(null). Optional.of(null) throws NullPointerException; map instead converts a null mapper result to empty.
How should an empty Optional be turned into an error?+
orElseThrow with the exception you choose, ideally with a message that names the missing thing. Avoid get(): it throws a bare NoSuchElementException with no context.