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 to mean "nothing here." The caller can easily forget to check for it. Then the program crashes with a NullPointerException.
This chapter introduces the tool Java gives you for this problem. It is called Optional. You will learn what it is, how to picture it, and what it changes about your code. Later chapters cover each of its methods in detail.
What Optional Is
Optional is a class in the java.util package. A class is a blueprint for objects. Java added Optional in version 8, which came out in 2014.
An Optional object is a container. A container is an object that holds other objects. Most containers, such as a List, can hold many items. An Optional is different. It holds at most one item.
That means an Optional is always in one of two states:
- Present: the box holds exactly one value.
- Empty: the box holds nothing.
There is no third state. An Optional never contains null as its value. If the value is missing, the Optional is empty.
A Picture to Keep in Mind
Think of a small gift box with a lid. Someone hands you the box. You cannot use the gift until you open the box and look inside. Maybe there is a gift, and maybe the box is empty.
The box itself always exists. That is the key idea. With null, there is no box at all, so there is nothing to hold onto. With Optional, you always get a real object back. You can safely ask that object, "Do you have something inside?"
The Type Name: Optional<T>
Optional is a generic class. A generic class is a class that works with any type you choose. You write the type inside angle brackets, just as you write List<String>.
The letter T stands for "type." You replace it with the real type of the value inside:
| Declaration | What it means |
|---|---|
| `Optional<String>` | Maybe a `String`, maybe nothing |
| `Optional<Integer>` | Maybe an `Integer`, maybe nothing |
| `Optional<Customer>` | Maybe a `Customer` object, maybe nothing |
The type name tells the reader something important. When you see Optional<String>, you know right away that the string might be missing. A plain String does not tell you that.
Why the Return Type Matters
The biggest benefit of Optional shows up in method signatures. A method signature is the first line of a method: its name, its parameters, and its return type.
Look at these two signatures:
String findNumber(String name)
Optional<String> findNumber(String name)The first one returns a String. Can it return null? You cannot tell from the signature. You would have to read the documentation or the code inside. Many people skip that step.
The second one returns an Optional<String>. The signature itself says, "I might not find a number." The compiler also helps you. A compiler is the program that turns your Java code into something the computer can run. You cannot treat an Optional<String> as a String by mistake. The compiler stops you, so you have to deal with the empty case.
| Row | Returns `String` (may be `null`) | Returns `Optional<String>` |
|---|---|---|
| Can the caller see that the value may be missing? | No, only from docs | Yes, from the type |
| Does the compiler force the caller to think about it? | No | Yes |
| What happens if the caller forgets? | `NullPointerException` at run time | Code does not compile |
| What does "missing" look like? | `null` | An empty `Optional` |
A Worked Example: A Phone Book
Let's build a small phone book two ways. First, the old way with null. Then the new way with Optional.
The null Version
import java.util.Map;
public class NullPhoneBook {
static final Map<String, String> NUMBERS = Map.of("Ada", "555-0101");
static String findNumber(String name) {
return NUMBERS.get(name); // returns null if the name is not found
}
public static void main(String[] args) {
String ada = findNumber("Ada");
System.out.println(ada.length()); // 8
String bob = findNumber("Bob");
System.out.println(bob.length()); // crashes with NullPointerException
}
}Map.get returns null when the key is not in the map. A key is the name you look up in the map. Nothing in findNumber's signature warns the caller. The second call crashes.
The Optional Version
import java.util.Map;
import java.util.Optional;
public class OptionalPhoneBook {
static final Map<String, String> NUMBERS = Map.of("Ada", "555-0101");
static Optional<String> findNumber(String name) {
return Optional.ofNullable(NUMBERS.get(name));
}
public static void main(String[] args) {
Optional<String> ada = findNumber("Ada");
Optional<String> bob = findNumber("Bob");
System.out.println(ada); // Optional[555-0101]
System.out.println(bob); // Optional.empty
System.out.println(ada.isPresent()); // true
System.out.println(bob.isPresent()); // false
System.out.println(bob.orElse("no number")); // no number
}
}Here is what changed:
findNumbernow returnsOptional<String>. Callers can see that the number may be missing.Optional.ofNullable(...)wraps the result from the map. If the map gave back a real string, theOptionalis present. If it gave backnull, theOptionalis empty. The next chapter covers this method and its siblings.- Printing an
Optionalshows its state. A present one prints asOptional[555-0101]. An empty one prints asOptional.empty. isPresent()asks the box whether it holds a value.orElse("no number")gives you the value if there is one, or the default text you supply if there is not. Nothing crashes.
How a Caller Works With an Optional
When a method returns an Optional, the caller follows a simple path. It gets the box. It deals with both possible states. Then it moves on with a real value.
This approach does not remove the "missing value" case. Values can still be missing. The difference is that the missing case is now out in the open, where you have to handle it.
Important Facts About Optional
A few rules about Optional will save you trouble later.
Optional Is Immutable
An immutable object is one that cannot change after it is created. Once you have an Optional, you cannot put a value into it or take one out. An empty Optional stays empty. Methods such as map and filter, which you will meet later, return a new Optional. They never change the old one.
An Optional Variable Should Never Be null
This rule is the most important one. The whole point of Optional is that you always get a real box back. If a method returns null where it promised an Optional, it breaks that promise. The caller will crash just as before.
// Wrong: the caller expects a box and gets nothing
static Optional<String> findNumber(String name) {
return null;
}Optional Is a Value-Based Class
The Java documentation calls Optional a "value-based" class. A value-based class is one where only the contents matter, not which exact object you have. Two practical rules follow:
- Compare Optionals with
equals, not==. The==operator checks whether two variables point to the same object.equalschecks whether they hold the same contents. - Do not use an
Optionalas a lock insynchronizedcode.
import java.util.Optional;
public class EqualsDemo {
public static void main(String[] args) {
Optional<String> a = Optional.of("Ada");
Optional<String> b = Optional.of("Ada");
System.out.println(a.equals(b)); // true: same contents
System.out.println(Optional.empty().equals(Optional.empty())); // true
}
}Optional Is Not Meant for Everything
The people who designed Optional built it for one main job: a return type for methods that might have no result. Java's own Optional is not Serializable. Serializable means it can be turned into bytes to save to a file or send over a network. That choice was deliberate. It hints that Optional does not belong in class fields that need to be saved. The last chapter of this tutorial covers where Optional fits and where it does not.
What Comes Next
You now know what an Optional is: a box that holds one value or nothing. The following chapters show how to use it:
- How to create Optionals with
of,ofNullable, andempty. - How to check whether a value is present.
- How to get the value out safely.
- How to transform the value without opening the box.
Exercise
A method has the signature Optional<Integer> findAge(String name). In plain words, what does this signature tell you that Integer findAge(String name) does not?
Show answer
It tells you that the age might be missing. The method returns either an Optional holding an Integer or an empty Optional. With the plain Integer version, you cannot tell from the signature whether the method might return null.
Exercise
What does this code print? Optional<String> x = Optional.ofNullable(null); System.out.println(x); System.out.println(x.isPresent());
Show answer
It prints "Optional.empty" and then "false". Wrapping null with ofNullable gives an empty Optional, so isPresent returns false.
Exercise
A teammate writes a method that returns Optional<String> but ends with return null; when nothing is found. Why is this a problem, and what should the method return instead?
Show answer
Callers expect a real Optional object and will call methods on it, such as isPresent. Calling a method on null throws a NullPointerException, so the Optional's promise is broken. The method should return an empty Optional, created with Optional.empty().