ProLesson 8.7Intermediate3 min readUpdated 30 October 2026
Optional, used correctly
Represent "maybe no value" without null. Create, transform and unwrap an Optional safely, and know where not to use it.
Optional<T> is a box that may or may not contain a value. It was added in Java 8 to make "there might be no result" explicit in a method's return type, so callers can't forget to handle it the way they forget to check for null.
01Creating an Optional
java
Optional<String> some = Optional.of("Asha"); // value must not be null
Optional<String> none = Optional.empty(); // no value
Optional<String> maybe = Optional.ofNullable(input); // empty if input is nullLoading the rest of the lesson…