Sub topic 3
Creating Optionals
In the last chapter you met Optional, a box that either holds one value or holds nothing. Before you can use that box, you need to make one. This chapter shows the three ways to do that and how to pick the right one.
You cannot create an Optional with new Optional<>(...). Its constructor is private, so code outside the class cannot call it. Java gives you three factory methods instead. A factory method is a static method that builds and returns an object for you. A static method is a method you call on the class itself, such as Optional.of(...), rather than on an object.
The three factory methods are:
| Method | What you pass in | What you get back |
|---|---|---|
| `Optional.of(value)` | A value that must not be null | An Optional holding that value |
| `Optional.empty()` | Nothing | An empty Optional |
| `Optional.ofNullable(value)` | A value that might be null | A full Optional if the value is not null, an empty one if it is |
All three live in the java.util package. You need import java.util.Optional; at the top of your file.
A First Look at All Three
Here is a short program that uses each method once.
import java.util.Optional;
public class CreateDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
Optional<String> none = Optional.empty();
String fromEnv = System.getenv("USER_NAME"); // may be null
Optional<String> maybe = Optional.ofNullable(fromEnv);
System.out.println(name.isPresent()); // true
System.out.println(none.isPresent()); // false
System.out.println(maybe.isPresent());
}
}The isPresent() method returns true when the box holds a value. The next chapter covers it in detail. Here it only shows what each box contains.
The last line prints false on most computers, because most systems have no environment variable called USER_NAME. If you set one before you run the program, it prints true. An environment variable is a named setting that your operating system passes to programs. System.getenv returns null when the variable does not exist. That makes it a good example of a value that might be null.
Optional.of: When You Know the Value Exists
Use Optional.of when you are sure the value is not null. A string literal like "Ada" is never null. Neither is an object you just made with new.
Optional<String> greeting = Optional.of("Hello");
Optional<StringBuilder> builder = Optional.of(new StringBuilder());What happens if you pass null
Optional.of checks its argument right away. If the argument is null, it throws a NullPointerException on that same line. This program shows it:
import java.util.Optional;
public class OfNullDemo {
public static void main(String[] args) {
String missing = null;
try {
Optional<String> box = Optional.of(missing);
System.out.println("Never printed: " + box);
} catch (NullPointerException e) {
System.out.println("Optional.of refused a null value");
}
}
}Output:
Optional.of refused a null valueThis might look like a problem, but it is useful. Suppose you believed a value could never be null and you were wrong. Optional.of tells you so on the exact line where the bad value came in. Without that check, the null could travel through your program and crash somewhere far away, where the cause is harder to find. Failing early like this is often called fail-fast behavior.
Optional.empty: When There Is No Value
Use Optional.empty() when you already know there is nothing to return. A common case is a search that found no match.
Optional<String> nothing = Optional.empty();You do not tell empty() the type in its parentheses. Java works it out from the variable on the left side. Here the variable is Optional<String>, so Java creates an empty Optional<String>. Working out a type from the surrounding code is called type inference.
When type inference needs help
Sometimes there is no variable on the left side for Java to read the type from. Look at this line:
String s = Optional.empty().orElse("fallback"); // does not compileorElse returns the value inside the box, or the fallback when the box is empty. Here Java has to decide the type of Optional.empty() before it can look at the rest of the line. With no other clue, it picks Optional<Object>. Then orElse returns an Object, and you cannot store an Object in a String variable. To fix this, give the type yourself by writing it in angle brackets just before the method name:
String s = Optional.<String>empty().orElse("fallback"); // compilesYou will not need this often. When you see a strange compile error about Object, though, this is usually the reason.
Every empty Optional is the same object
The Java library keeps one shared empty Optional, and Optional.empty() hands that one back every time. This saves memory. It is also safe, because Optionals are immutable, which means they never change after they are created. No piece of code can put a value into the shared empty box and affect anyone else.
Optional.ofNullable: When You Are Not Sure
Use Optional.ofNullable when a value might be null and you cannot control that. This happens all the time with older Java methods that return null to mean "not found":
Map.get(key)returns null when the key is missing.System.getenv(name)returns null when the variable is not set.- Many older libraries return null from their lookup methods.
ofNullable makes a choice for you. It behaves like this code:
// What Optional.ofNullable(value) does, in plain Java
value == null ? Optional.empty() : Optional.of(value)It never throws an exception. A null value gives you an empty box, and any other value gives you a full one.
Wrapping an older method
The most common job for ofNullable is to wrap a method that returns null, so that callers get an Optional instead. Here a map lookup is turned into a method that returns Optional<String>:
import java.util.Map;
import java.util.Optional;
public class WrapDemo {
static final Map<Integer, String> USERS = Map.of(
1, "ada",
2, "grace");
static Optional<String> findUser(int id) {
return Optional.ofNullable(USERS.get(id));
}
public static void main(String[] args) {
System.out.println(findUser(1)); // Optional[ada]
System.out.println(findUser(7)); // Optional.empty
}
}USERS.get(7) returns null because no user has id 7. ofNullable turns that null into an empty Optional. Anyone who calls findUser can see from its return type that a user might not be found. They do not have to guess or read the documentation.
Choosing the Right Method
The diagram below shows the choice as two questions.
You could use ofNullable everywhere, since it handles both cases. Most programmers still prefer of when the value cannot be null. It tells the reader "this value is here," and it catches mistakes. If you use ofNullable on a value that should never be null, a bug can hide as an empty Optional and nobody notices.
Printing and Comparing Optionals
Two more details help when you test and debug your code.
Printing. An Optional's toString() method shows what is inside. A full Optional prints as Optional[value], and an empty one prints as Optional.empty.
Comparing. The equals method compares what is inside the boxes. Two Optionals are equal when both are empty, or when both hold values that are equal to each other.
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");
Optional<String> e1 = Optional.empty();
Optional<String> e2 = Optional.ofNullable(null);
System.out.println(a); // Optional[Ada]
System.out.println(e1); // Optional.empty
System.out.println(a.equals(b)); // true
System.out.println(e1.equals(e2)); // true
System.out.println(a.equals(e1)); // false
}
}The Most Important Rule: Never Return a Null Optional
A method that returns Optional makes a promise: "I will always give you a box, and you only need to check what is inside." If the method returns null itself, it breaks that promise. Callers will write findUser(7).isPresent() and get a NullPointerException. That is the very problem Optional exists to prevent.
// Wrong: breaks the promise of the return type
static Optional<String> badFind(int id) {
if (id < 0) {
return null;
}
return Optional.ofNullable(USERS.get(id));
}
// Right: always return a box, even when it is empty
static Optional<String> goodFind(int id) {
if (id < 0) {
return Optional.empty();
}
return Optional.ofNullable(USERS.get(id));
}Quick Reference
| Situation | Method to use | Example |
|---|---|---|
| Value is a literal or a new object | `Optional.of` | `Optional.of("Ada")` |
| A search found nothing | `Optional.empty` | `return Optional.empty();` |
| Result of `Map.get` or an older API | `Optional.ofNullable` | `Optional.ofNullable(map.get(k))` |
| You need the type in a chain | `Optional.<T>empty` | `Optional.<String>empty().orElse("x")` |
Exercise
What does this code print, and why? String s = null; Optional<String> a = Optional.ofNullable(s); Optional<String> b = Optional.of(s); System.out.println(a);
Show answer
Nothing is printed. The ofNullable line works and makes an empty Optional. The next line, Optional.of(s), throws a NullPointerException because s is null, so the program stops before it reaches the println.
Exercise
You are writing a method Optional<String> findEmail(String user) that reads from a Map<String, String> called emails. Which factory method should it use, and what does the return line look like?
Show answer
Use Optional.ofNullable, because emails.get(user) returns null when the user has no entry. The line is: return Optional.ofNullable(emails.get(user));
Exercise
Why does String s = Optional.empty().orElse("none"); fail to compile, and how do you fix it?
Show answer
With no other clue, Java treats Optional.empty() as Optional<Object>, so orElse returns an Object, and an Object cannot be stored in a String variable. Give the type yourself: String s = Optional.<String>empty().orElse("none");
Exercise
Is Optional.empty().equals(Optional.ofNullable(null)) true or false?
Show answer
True. Both are empty Optionals, and equals treats two empty Optionals as equal.