Sub topic 2
Meet Optional: A Container for Maybe-Values
In the last chapter you saw how null causes trouble. A method can return null, and nothing in its signature warns you. If you forget to check, your program crashes with a NullPointerException. This chapter introduces the tool Java provides for this problem.
What Optional Is
Optional is a class in the java.util package. It has been part of Java since Java 8. An Optional is a container object, which means an object whose job is to hold another object.
An Optional is like a small box. The box is always there. When you open it, you find one of two things:
- One value inside. We say the Optional is present.
- Nothing inside. We say the Optional is empty.
The box itself is never null. Only its contents can be missing. That is the main idea of this chapter.
The Type Tells the Story
Optional is a generic type. A generic type is a type that takes another type as a parameter, the way List<String> is a list of strings. So Optional<String> means "a box that may hold a String." Likewise, Optional<Integer> may hold an Integer.
Compare these two method signatures:
String findNickname(String userId);
Optional<String> findNicknameSafely(String userId);The first one looks like it always returns a String. It might return null, but you can only find that out by reading the documentation or the code. The second one says in its return type that the nickname might not exist. The compiler then makes you deal with the box before you can reach the String inside.
A Worked Example
Here is a small program. It looks up nicknames in a map. When it finds a nickname, it returns a box holding it. When it doesn't, it returns an empty box instead of null.
import java.util.Map;
import java.util.Optional;
public class NicknameDemo {
static final Map<String, String> NICKNAMES = Map.of("u1", "Ada");
static Optional<String> findNickname(String userId) {
String nick = NICKNAMES.get(userId); // may be null
if (nick == null) {
return Optional.empty();
}
return Optional.of(nick);
}
public static void main(String[] args) {
Optional<String> found = findNickname("u1");
Optional<String> missing = findNickname("u2");
System.out.println(found); // Optional[Ada]
System.out.println(missing); // Optional.empty
}
}Run it, and you get two lines of output. The first box prints as Optional[Ada], which shows the value inside. The second prints as Optional.empty. Neither call returned null, so the program can safely call methods on both results.
The next chapters cover Optional.of and Optional.empty in detail, along with the safe ways to get values out.
Two Rules to Remember
Rule 1: Never set an Optional variable to null. An Optional exists so you can stop using null. If you write Optional<String> x = null;, you bring the original problem back. Use an empty Optional instead.
Rule 2: An Optional cannot be changed. Optional is immutable, which means that once it is created, its contents never change. You cannot put a value into an empty box later. If you need a different value, you make a new Optional.
Summary
| Idea | Meaning |
|---|---|
| `Optional<T>` | A box that may hold one value of type `T` |
| Present | The box holds a value |
| Empty | The box holds no value |
| Never null | The box itself is always a real object |
| Immutable | The contents cannot change after creation |
Exercise
A method has the signature Optional<Integer> findAge(String name). What does the return type tell you, and should this method ever return null?
Show answer
The return type tells you the age might not be found, so the result could be an empty Optional. The method should never return null. When no age exists, it should return an empty Optional.
Exercise
What does System.out.println print for an Optional holding "Bob", and for an empty Optional?
Show answer
It prints Optional[Bob] for the Optional holding "Bob" and Optional.empty for the empty one.