Optionals — cheat sheet
From: fundamentals/07-optionals.md.
- What it is: a container that either holds a value or is empty — a method returns
Optional<T>instead ofTwhen it might legitimately have nothing to give back. The method signature itself then tells callers "check before you use this," instead of relying on convention or documentation. - Creating:
Optional.of(value)when there's something to return,Optional.empty()when there isn't. Nonew+ constructor — only these static factories. - Using:
isPresent()/isEmpty()to check,get()to unwrap once you know it's present,orElse(fallback)to unwrap with a default if empty. - Where to use it: only as a return type, for methods that sometimes genuinely have nothing to return. Not for method parameters (except in test code) and not for fields on data classes.
- Why not just
null?: before Java 8,nullwas the only way to represent "nothing," and it could appear almost anywhere with no signal in the method signature — leading to defensivenull-checking everywhere ("null paranoia"), since you could never be sure from the signature alone whether a given call might returnnull.Optionalmakes the "might be empty" case explicit and type-checked instead of implicit and undocumented.