Optional
Optional<T> is a box that may hold a value or be empty. Return it from a method that might not find a result, instead of returning null or throwing.
Detailed Explanation
null is a legal reference and a common crash. A method that returns User might mean "here is a user" or "I used null for not found". The caller cannot see the difference in the type. Optional<User> makes the maybe visible. The caller must unwrap.
Create with Optional.of(value) (rejects null), Optional.ofNullable(value), or Optional.empty(). Read with orElse(default), orElseGet(supplier), orElseThrow(), ifPresent, and ifPresentOrElse. Transform with map, flatMap, and filter. Those methods skip the function when the box is empty, which is why Optional chains look like a tiny stream.
orElse always evaluates its argument. orElseGet evaluates the supplier only when empty. That difference matters when the default is expensive or has a side effect (orElse(loadFromDb()) hits the database even on a hit).
Optional is a return type. It is not a field you persist, not a method parameter, and not an element type for a list (List<Optional<User>> is a smell). Do not call get() without isPresent(); orElseThrow states the failure. Do not return Optional from a getter on a field that is never null.
You reach for Optional on lookups (findById), on stream terminals (findFirst, max), and on parse helpers that should not throw. You keep null for private fields in a class that already documents unset state, or you use a dedicated empty object. You throw when absence is a bug (Objects.requireNonNull on a constructor argument).
The cost of Optional is an extra object and a style that can nest (Optional<Optional<T>> means you wanted flatMap). Primitive specializations (OptionalInt) avoid boxing a single int. Serializing Optional as a bean field surprises Jackson unless you configure it. Keep Optional at the method boundary, unwrap at the edge, and continue with a plain value or a thrown exception.
Code Examples
import java.util.Optional;
public class Find {
static Optional<String> nick(String id) {
if ("u1".equals(id)) {
return Optional.of("ana");
}
return Optional.empty();
}
public static void main(String[] args) {
String shown = nick("u1").orElse("anonymous");
String missing = nick("nope").orElse("anonymous");
System.out.println(shown); // prints: ana
System.out.println(missing); // prints: anonymous
System.out.println(nick("u1").map(String::toUpperCase).orElse("?")); // prints: ANA
}
}import java.util.List;
import java.util.Optional;
public class First {
public static void main(String[] args) {
Optional<String> first = List.of("a", "bb", "c").stream()
.filter(s -> s.length() > 1)
.findFirst();
first.ifPresent(System.out::println); // prints: bb
}
}Common Gotchas
`orElse(compute())` always runs `compute`
use `orElseGet(() -> compute())` for lazy defaults.
`get()` on an empty Optional throws `NoSuchElementException`
prefer `orElseThrow`.
Do not use Optional as a field or parameter
it adds allocation and does not help the caller who must still unwrap.
`Optional.of(null)` throws `NullPointerException`
use `ofNullable` when the value might be null.