Sub topic 3
Creating Optionals
An Optional is a box that holds either one value or nothing. Before you can use that box, you need to make one. Java gives you three factory methods for this. A factory method is a static method that builds an object for you, so you never write new Optional.
The three methods are:
Optional.of(value)makes a box with a value inside. The value must not be null.Optional.empty()makes an empty box.Optional.ofNullable(value)makes a box that is full if the value is not null, and empty if it is null.
All three live in the java.util package, so add import java.util.Optional; at the top of your file.
Optional.of: When You Know There Is a Value
Use Optional.of when you are sure the value exists. For example, you might have a name typed right into your code, or a value you have already checked.
import java.util.Optional;
public class OfDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
System.out.println(name); // Optional[Ada]
}
}The type Optional<String> means "a box that may hold a String." The part in angle brackets is a generic type parameter. It tells Java what kind of value can go in the box.
If you pass null to Optional.of, it throws a NullPointerException straight away. That can look harsh, but it helps you. You find the bug at the exact line where the null showed up, not three methods later.
import java.util.Optional;
public class OfNullDemo {
public static void main(String[] args) {
String missing = null;
try {
Optional<String> bad = Optional.of(missing);
} catch (NullPointerException e) {
System.out.println("Optional.of refused null");
}
}
}Optional.empty: When There Is No Value
Use Optional.empty() when you want to say clearly that there is no result. A search method might return it when it finds nothing.
import java.util.Optional;
public class EmptyDemo {
static Optional<String> findNickname(String user) {
if (user.equals("grace")) {
return Optional.of("Amazing Grace");
}
return Optional.empty();
}
public static void main(String[] args) {
System.out.println(findNickname("grace")); // Optional[Amazing Grace]
System.out.println(findNickname("bob")); // Optional.empty
}
}Whoever calls findNickname can tell from its return type that a nickname might not exist.
Optional.ofNullable: When You Are Not Sure
Many older Java methods return null when they have nothing to give back. System.getenv is one of them. It reads an environment variable, which is a named setting supplied by your operating system, and it returns null if the variable is not set. Map.get also returns null when a key is missing. Optional.ofNullable wraps these results safely.
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 last line prints true if USER_NAME is set on your computer and false if it is not. Both cases run without a crash. The isPresent method is covered in the next chapter. For now, read it as "is there a value in the box?"
Choosing the Right Method
| Method | Input | Result |
|---|---|---|
| `Optional.of(x)` | non-null `x` | box holding `x` |
| `Optional.of(null)` | null | throws `NullPointerException` |
| `Optional.empty()` | nothing | empty box |
| `Optional.ofNullable(x)` | non-null `x` | box holding `x` |
| `Optional.ofNullable(null)` | null | empty box |
Exercise
A method gets a phone number from a Map with phoneBook.get(name). The name might not be in the map. Which factory method should wrap the result, and what happens if you use Optional.of instead?
Show answer
Use Optional.ofNullable(phoneBook.get(name)), because Map.get returns null when the key is missing. With Optional.of, a missing name gives null, and Optional.of(null) throws a NullPointerException.
Exercise
What does this line print? System.out.println(Optional.ofNullable(null).isPresent());
Show answer
It prints false. ofNullable turns null into an empty Optional, and an empty Optional has no value present.