Optional
A container that holds either one value or nothing, used as a return type to make "no result" visible to the caller.
In more detail
Optional.of wraps a value that must not be null, Optional.empty represents absence, and Optional.ofNullable adapts an older API that may return null. map, filter and flatMap transform the value only if it is present, and orElse supplies a fallback. Use it for lookups that may find nothing; do not use it for every field or parameter, and do not call get without knowing a value exists.
Examples
Optional<String> value = Optional.empty();find().map(String::toUpperCase).orElse("MISSING")Related terms
- orElse — The Optional methods that turn an Optional back into a plain value: orElse with a fallback, orElseGet with a fallback computed only if needed, and orElseThrow with an exception.
- null — A special value meaning no value or no object, set on purpose to show that something is empty or absent.
- flatMap — An operation that turns each element into a stream, or an Optional, and joins the results into one flat stream, removing a level of nesting.
- NullPointerException — The unchecked exception thrown when code uses a null reference as if it pointed to an object.
Taught in
- Handling Nulls With Optional — Modern Java: Virtual Threads & High-Throughput Services
- The Cost Of Checked Exceptions — Modern Java: Virtual Threads & High-Throughput Services
- Tying It All Together — Modern Java: Virtual Threads & High-Throughput Services
- Switch, Loops And Labels — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Interfaces: Default, Static And Private Methods — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Lambdas, Functional Interfaces And Method References — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Stream Pipelines, Primitive Streams And Optional — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Reduction, Grouping And Partitioning — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Sprint: Lambdas And Streams — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Platform And Virtual Threads, Runnable And Callable — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Paths And Files With NIO.2 — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Locales, Resource Bundles And Formatting — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Mock Exam: Sit It, Score It — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Final Review And Exam Day — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep