Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
Optional for the OCP 21 exam: creating with of, ofNullable and empty, checking with isPresent and isEmpty, unwrapping with get, orElse, orElseGet and orElseThrow, ifPresent and ifPresentOrElse, and chaining map, filter, flatMap, or and stream.
kvi5hnuCode Sprout team member6 min readOn this page
Some questions have no answer. What's the average score of a course with no exams yet? Who's the member with ID 999 when no such member exists? What's the largest element of an empty list?
Returning 0 would be wrong, and returning null is easy to misuse. A caller who forgets to check gets a NullPointerException somewhere far away. java.util.Optional<T> makes "there might be no value" part of the type. An Optional is a box that holds either one non-null value or nothing.
Streams use it everywhere: findFirst, min, max and reduce without an identity all return an Optional. That's why this chapter starts here.
Creating an Optional
Optional has no public constructor (new Optional<>(x) doesn't compile). There are three static factory methods:
| Factory | Result |
|---|---|
Optional.of(value) | a box holding value. Throws NullPointerException if value is null |
Optional.ofNullable(value) | Optional.of(value), or an empty box if value is null |
Optional.empty() | an empty box |
static Optional<Double> average(int... scores) {
if (scores.length == 0) return Optional.empty();
int sum = 0;
for (int s : scores) sum += s;
return Optional.of((double) sum / scores.length);
}
System.out.println(average(88, 93, 79)); // Optional[86.66666666666667]
System.out.println(average()); // Optional.empty
Optional.ofNullable(map.get(key)) replaces the old pattern value == null ? Optional.empty() : Optional.of(value).
Getting the value out

| Method | Empty | Has a value |
|---|---|---|
get() | throws NoSuchElementException | returns the value |
isPresent() | false | true |
isEmpty() (Java 11) | true | false |
ifPresent(Consumer) | does nothing | calls the consumer with the value |
ifPresentOrElse(Consumer, Runnable) (Java 9) | runs the Runnable | calls the consumer |
orElse(T other) | returns other | returns the value |
orElseGet(Supplier<T>) | returns supplier.get() | returns the value |
orElseThrow() (Java 10) | throws NoSuchElementException | returns the value |
orElseThrow(Supplier<X>) | throws the exception the supplier creates | returns the value |
Optional<Double> avg = average(70, 81);
if (avg.isPresent()) System.out.println(avg.get()); // 75.5: the old-fashioned way
avg.ifPresent(System.out::println); // 75.5: same intent, no if
Optional<Double> none = average();
none.get(); // NoSuchElementException: No value present
none.orElse(Double.NaN); // NaN
none.orElseGet(() -> 50.0); // 50.0
none.orElseThrow(() -> new IllegalStateException("no exams")); // throws IllegalStateException
Details the exam checks:
- Types must match. On an
Optional<Double>,orElseneeds aDouble.orElse(1)doesn't compile, because anintcan't be boxed to aDouble, andorElseGet(() -> new IllegalStateException())doesn't compile because the supplier returns the wrong type. - The supplier returns the exception, and
orElseThrowthrows it.orElseThrow(() -> new IllegalStateException())andorElseThrow(IllegalStateException::new)are correct.orElseThrow(() -> throw new X())doesn't compile. - Checked exceptions follow the usual rules.
orElseThrow(Exception::new)compiles only if the calling method handles or declaresException. orElsealways evaluates its argument, even when the value is present.orElse(expensiveDefault())calls the method every time, whileorElseGet(() -> expensiveDefault())calls it only when theOptionalis empty.- When the
Optionalhas a value, everyorElse…variant simply returns it.
Chaining: map, filter, flatMap
Optional has three methods that work like their stream equivalents (articles 62 and 63). Each one passes an empty Optional straight through:
| Method | If a value is present |
|---|---|
filter(Predicate) | keeps it if the predicate is true, otherwise returns empty |
map(Function) | returns Optional.ofNullable(f.apply(value)). A null result becomes empty |
flatMap(Function) | returns f.apply(value), which must already be an Optional |
Nested if statements become one readable chain:
// print the number only if it has exactly three digits
optional.map(n -> "" + n)
.filter(s -> s.length() == 3)
.ifPresent(System.out::println);
Use flatMap when the function itself returns an Optional. With map, you'd get an Optional<Optional<...>>:
static Optional<String> domainOf(String email) { ... }
Optional<String> email = ...;
Optional<Optional<String>> nested = email.map(Solution::domainOf); // compiles, but awkward
Optional<String> domain = email.flatMap(Solution::domainOf); // flattened
Optional<String> wrong = email.map(Solution::domainOf); // DOES NOT COMPILE
Optional<Integer> bad = email.flatMap(String::length); // DOES NOT COMPILE: int isn't an Optional
or and stream (Java 9)
or(Supplier<Optional<T>>)returns thisOptionalif it has a value, and otherwise the otherOptional, which may itself be empty. UnlikeorElse, the result is still anOptional, so you can keep chaining.stream()returns a stream of zero or one element. That's handy for dropping the empty ones from a stream ofOptionals:optionals.flatMap(Optional::stream).
Optional<Member> who = findMember(3).or(() -> findMember(2)); // falls back to member 2
Stream.of(Optional.of(1), Optional.empty(), Optional.of(3))
.flatMap(Optional::stream)
.toList(); // [1, 3]
Using Optional well
- Return
Optionalfrom methods that may have no result. That's what it was designed for. - Don't use
Optionalfor fields, method parameters or collection elements. It isn'tSerializable, and it adds overhead. An empty collection is better than anOptional<List<…>>. - Never return
nullfrom a method declared to returnOptional. - For primitives there are
OptionalInt,OptionalLongandOptionalDouble, withgetAsInt()and similar methods. They come from primitive streams and are covered in article 64. Optionalis generic and invariant like everything else: anOptional<String>isn't anOptional<Object>.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Optionalgainedor,ifPresentOrElseandstreamin Java 9,orElseThrow()with no arguments in Java 10 andisEmptyin Java 11. It's still meant for return types, not for fields or parameters.
Exam traps from this article
A complete example
The program returns Optional from a lookup method and an average method. It unwraps them with each method from the table, shows that orElse evaluates its argument eagerly while orElseGet doesn't, and chains map, flatMap and filter. It also uses or for a fallback and stream for the zero-or-one case.
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
public class Solution {
record Member(String name, String email) {}
private static final Map<Integer, Member> MEMBERS = Map.of(
1, new Member("Rina", "rina@example.org"),
2, new Member("Teo", null)); // Map.of forbids null values, so this one is inside the record
// Returning Optional makes "maybe no result" part of the method's type
static Optional<Member> findMember(int id) {
return Optional.ofNullable(MEMBERS.get(id));
}
static Optional<Double> average(int... scores) {
if (scores.length == 0) return Optional.empty();
int sum = 0;
for (int s : scores) sum += s;
return Optional.of((double) sum / scores.length);
}
// A helper that itself returns Optional: chain it with flatMap
static Optional<String> domainOf(String email) {
int at = email.indexOf('@');
return at < 0 ? Optional.empty() : Optional.of(email.substring(at + 1));
}
static String describe(int id) {
return findMember(id)
.map(Member::email) // Optional<String>, empty if email is null
.flatMap(Solution::domainOf) // Optional<String>, not Optional<Optional<String>>
.filter(d -> d.endsWith(".org"))
.map(d -> "member " + id + " uses " + d)
.orElse("member " + id + ": no .org address");
}
public static void main(String[] args) {
// Creating and printing
System.out.println(average(88, 93, 79) + " " + average());
// Checking and unwrapping
Optional<Double> avg = average(70, 81);
if (avg.isPresent()) System.out.println("isPresent/get: " + avg.get());
avg.ifPresent(v -> System.out.println("ifPresent: " + v));
average().ifPresentOrElse(
v -> System.out.println("never printed"),
() -> System.out.println("ifPresentOrElse: no scores yet"));
// Defaults for an empty Optional
Optional<Double> none = average();
System.out.println("orElse: " + none.orElse(Double.NaN)
+ ", orElseGet: " + none.orElseGet(() -> 50.0)
+ ", isEmpty: " + none.isEmpty());
try {
none.orElseThrow();
} catch (NoSuchElementException e) {
System.out.println("orElseThrow(): " + e.getMessage());
}
try {
none.orElseThrow(() -> new IllegalStateException("no exams taken"));
} catch (IllegalStateException e) {
System.out.println("orElseThrow(supplier): " + e.getMessage());
}
// orElse always evaluates its argument; orElseGet only when empty
int[] calls = {0};
avg.orElse(expensiveDefault(calls));
avg.orElseGet(() -> expensiveDefault(calls));
System.out.println("expensiveDefault ran " + calls[0] + " time(s)");
// Chaining map, flatMap and filter
for (int id : List.of(1, 2, 3)) System.out.println(describe(id));
// or() supplies a fallback Optional; stream() turns it into 0 or 1 elements
Optional<Member> anyone = findMember(3).or(() -> findMember(2));
System.out.println("or: " + anyone.map(Member::name).orElse("nobody")
+ ", stream count: " + findMember(3).stream().count());
}
static double expensiveDefault(int[] calls) {
calls[0]++;
return -1;
}
}
Output:
Optional[86.66666666666667] Optional.empty
isPresent/get: 75.5
ifPresent: 75.5
ifPresentOrElse: no scores yet
orElse: NaN, orElseGet: 50.0, isEmpty: true
orElseThrow(): No value present
orElseThrow(supplier): no exams taken
expensiveDefault ran 1 time(s)
member 1 uses example.org
member 2: no .org address
member 3: no .org address
or: Teo, stream count: 0
Points to notice:
expensiveDefaultran once: fromorElse, even thoughavghad a value.orElseGetnever called it.- For member 2, the email is
null, somap(Member::email)produced an emptyOptional, and the chain fell through toorElse. flatMap(Solution::domainOf)kept the result a flatOptional<String>.- Member 3 doesn't exist, so
orfell back to member 2, andfindMember(3).stream()had zero elements.
Common questions
Should I use isPresent() + get()?
It works, and exam code uses it, but ifPresent, map and the orElse… methods say the same thing more safely. They can't forget the check.
What's the difference between orElse(null) and get()?
orElse(null) turns an empty Optional back into null without throwing. That's sometimes needed when you call older APIs. get() throws instead.
Does Optional.equals compare values?
Yes. Two Optionals are equal if both are empty or both hold equal values, so Optional.empty().equals(Optional.ofNullable(null)) is true.
Summary
- Create with
Optional.of(non-null),Optional.ofNullable(maybe null) orOptional.empty(). - Check with
isPresent/isEmpty, act withifPresent/ifPresentOrElse, and unwrap withorElse,orElseGet,orElseThroworget. get()andorElseThrow()throwNoSuchElementExceptionwhen empty.orElseThrow(supplier)throws your exception.map,filterandflatMaptransform the value and pass emptiness along. UseflatMapwhen the function already returns anOptional.orprovides a fallbackOptional, andstreamgives zero or one element.
Practice quiz
Test yourself with the Optional quiz: 10 exam-style questions with explanations.
Previous: Java Generic Wildcards: Unbounded, Upper-Bounded and Lower-Bounded Types (OCP 21)
Next: Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
Related reading
- Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
- Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
- Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
- Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
- Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.