Optional
Optional is a box that either holds one value or nothing, and it exists so that "there is no value" is a case the type system makes a caller think about. A method that returns a String and may answer null says nothing about the null in its signature; a method that returns Optional<String> says the absence is expected.
Creating an Optional
Three factories: of for a value that is there, ofNullable for one that may be null, and empty for nothing. of(null) throws at once, which is the point: it is the form for a value the caller guarantees.
import java.util.Optional;
public class Create {
public static void main(String[] args) {
Optional<String> named = Optional.of("Ada");
Optional<String> maybe = Optional.ofNullable(null);
Optional<String> empty = Optional.empty();
System.out.println(named.isPresent() + " " + named.get());
System.out.println(maybe.isPresent() + " " + empty.isEmpty());
System.out.println(named.orElse("none"));
System.out.println(maybe.orElse("none"));
System.out.println(maybe.orElseGet(() -> "computed"));
try {
maybe.orElseThrow(() -> new IllegalStateException("missing"));
} catch (IllegalStateException e) {
System.out.println("orElseThrow: " + e.getMessage());
}
}
}
javac -Xlint:all Create.java
java Create
true Ada
false true
Ada
none
computed
orElseThrow: missing
The two words on the second line are the two ways to ask about the box, and both exist because a condition reads better in one of them depending on the code around it. orElse takes a value and orElseGet takes a supplier, which matters when the fallback is expensive: the supplier runs only when it is needed, while the value of orElse is computed before the call whether it is used or not.
Reading a value that may be absent
get is the one method to avoid: it throws when the box is empty, which is exactly the null check the type was supposed to remove. The program below shows what it throws, and then the three methods that read without a surprise:
import java.util.Optional;
public class Get {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
try {
empty.get();
} catch (java.util.NoSuchElementException e) {
System.out.println("get: " + e.getClass().getSimpleName());
}
System.out.println(empty.orElse("default"));
System.out.println(empty.isPresent());
}
}
javac -Xlint:all Get.java
java Get
get: NoSuchElementException
default
false
NoSuchElementException is a RuntimeException, so a caller who forgets it compiles and fails later. The three alternatives are a default with orElse, an exception the caller chooses with orElseThrow, and a body that runs only when the value is there, with ifPresent or ifPresentOrElse.
map, filter and the chain
Optional has the two lazy steps of a stream and one terminal read, so a value that may be missing can be transformed without a null check at each step. The two helpers below are the pattern in its usual shape:
import java.util.Optional;
public class Chain {
public static void main(String[] args) {
System.out.println(length("hello"));
System.out.println(length(null));
System.out.println(upperFirst("ada"));
System.out.println(upperFirst(""));
Optional<String> name = Optional.of(" grace ");
System.out.println(name.map(String::strip).map(String::toUpperCase).orElse("?"));
System.out.println(name.filter(s -> s.length() > 20).isPresent());
name.ifPresent(s -> System.out.println("present: [" + s + "]"));
Optional.empty().ifPresent(s -> System.out.println("never"));
Optional.of("x").ifPresentOrElse(
s -> System.out.println("value " + s),
() -> System.out.println("nothing"));
}
static Optional<Integer> length(String text) {
return Optional.ofNullable(text).map(String::length);
}
static String upperFirst(String text) {
return Optional.of(text)
.filter(s -> !s.isEmpty())
.map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
.orElse("empty");
}
}
javac -Xlint:all Chain.java
java Chain
Optional[5]
Optional.empty
Ada
empty
GRACE
false
present: [ grace ]
value x
map on an empty Optional does nothing and answers an empty one, which is why length(null) prints Optional.empty instead of throwing: the chain is a null check per step without a branch. The filter keeps or empties the box, the printing line shows the value unstripped because ifPresent reads the box as it is, and the last two lines are the two-branch form.
When not to use Optional
Optional is designed for the return type of a method that may find nothing, such as a lookup or a parse. It does not belong in a field, in a parameter of a method that the caller always has a value for, or in a collection: a List<Optional<T>> is a list with a second way to be empty, and Optional is not serialisable. Lesson 094 takes the field and the parameter apart with programs.
The other rule is that an Optional is a value like any other: it is not a null check to be unwrapped at the first line. A method that calls get immediately after receiving an Optional has the exception the type was meant to prevent, one line later.
Exercises
- Write a method that parses a string to an int and returns an OptionalInt, and print the result for a good and a bad input.
- Replace the orElse("?") of Chain with orElseGet and print the same line.
- Use map to turn an Optional of a name into an Optional of its length, then print both.
- Write the same method as upperFirst with an if and a ternary, and compare the two versions.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Optional.ofNullable(x)answer for a null x?Answer
An empty Optional
ofNullable is the factory for a value that may be null, and it maps null to empty.
-
What does
orElseGetadd overorElse?Answer
The fallback is computed only when it is needed
orElse takes a value that is already computed; orElseGet takes a supplier.
-
Why should
getbe avoided?Answer
It throws on an empty Optional, which is the null check the type removed
The exception is unchecked, so the failure appears far from the call.
-
What does this program print?
import java.util.Optional; public class Q1 { public static void main(String[] args) { Optional<String> value = Optional.of("a"); System.out.println(value.map(String::toUpperCase).orElse("none")); System.out.println(Optional.<String>empty().map(String::toUpperCase).orElse("none")); } }Answer
A / none
The map applies to the value and does nothing to the empty box.
-
What does this program print?
import java.util.Optional; public class Q2 { public static void main(String[] args) { Optional<Integer> number = Optional.of(4); System.out.println(number.filter(n -> n > 10).isPresent()); System.out.println(number.filter(n -> n > 2).isPresent()); } }Answer
false / true
The filter empties the box when the predicate fails and keeps it otherwise.
-
What does this program print?
import java.util.Optional; public class Q3 { public static void main(String[] args) { System.out.println(Optional.empty().orElse("d")); System.out.println(Optional.of("v").orElse("d")); } }Answer
d / v
orElse answers the fallback only when the box is empty.
-
What does this program print?
import java.util.Optional; public class Q4 { public static void main(String[] args) { Optional<String> empty = Optional.empty(); try { empty.get(); } catch (java.util.NoSuchElementException e) { System.out.println("empty"); } } }Answer
empty
get on an empty Optional throws, and the catch prints its line.
-
What does this program print?
import java.util.Optional; public class Q5 { public static void main(String[] args) { StringBuilder log = new StringBuilder(); Optional.of("x").ifPresent(s -> log.append("value ")); Optional.<String>empty().ifPresent(s -> log.append("never ")); System.out.println("[" + log + "]"); } }Answer
[value ]
Only the present Optional runs its body, and the other leaves the log alone.
-
Where does an Optional belong?
Answer
As the return type of a method that may find nothing
The type marks a lookup that can fail to find, which is what a caller must handle.
-
What does
mapanswer on an empty Optional?Answer
An empty Optional of the new type
There is nothing to transform, so the emptiness passes through the step.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev