Sub topic 5
Getting the Value Out Safely
An Optional is a box that may hold a value. Sooner or later you need the value itself, for example to print it or save it. This chapter shows four ways to take a value out of an Optional. One of them is risky. The other three are safe.
The risky way: get
The get method returns the value inside the Optional. If the Optional is empty, get throws an exception. An exception is an error that stops your program unless you catch it. Here the exception is a NoSuchElementException.
import java.util.Optional;
public class GetDemo {
public static void main(String[] args) {
Optional<String> full = Optional.of("Ada");
System.out.println(full.get()); // Ada
Optional<String> empty = Optional.empty();
System.out.println(empty.get()); // throws NoSuchElementException
}
}If you use get without checking first, you get the same kind of crash that null gives you, only with a different exception name. That is why most Java developers avoid get.
The safe ways
Each safe method answers the same question: "What should happen if the box is empty?"
| Method | What it returns when empty | Good for |
|---|---|---|
| `orElse(value)` | The default value you pass in | Simple, fixed defaults like `"Unknown"` |
| `orElseGet(supplier)` | The result of calling a supplier | Defaults that take work to build |
| `orElseThrow(supplier)` | Nothing. It throws your chosen exception | Cases where a missing value is a real error |
A supplier is a small function that takes no input and returns a value. You usually write it as a lambda, such as () -> "Computed default".
When the Optional is full, all three methods return the value inside it.
A worked example
This program uses each safe method on an empty Optional.
import java.util.Optional;
public class RetrieveDemo {
public static void main(String[] args) {
Optional<String> city = Optional.empty();
String a = city.orElse("Unknown");
String b = city.orElseGet(() -> "Computed default");
System.out.println(a); // Unknown
System.out.println(b); // Computed default
try {
city.orElseThrow(() -> new IllegalStateException("No city"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No city
}
}
}Here is what happens, step by step:
cityis empty.orElse("Unknown")finds no value, so it returns"Unknown".orElseGet(...)finds no value, so it calls the lambda and returns"Computed default".orElseThrow(...)finds no value, so it throws anIllegalStateExceptionwith the message"No city". Thecatchblock prints that message.
If you change the first line to Optional.of("Paris"), all three calls return "Paris", and no exception is thrown.
Picking the right method
Use orElseThrow when your code cannot continue without the value, for example when a user ID must exist. Use orElse for a plain default. Use orElseGet when building the default takes real work. A later chapter explains why that difference matters.
Exercise
What does this code print? Optional<String> name = Optional.of("Lin"); System.out.println(name.orElse("Guest"));
Show answer
It prints "Lin". The Optional holds a value, so orElse returns that value and ignores the default "Guest".
Exercise
You load an order by ID, and a missing order means a bug in the caller. Which method should you use to get the order out of the Optional, and why?
Show answer
Use orElseThrow, for example orElseThrow(() -> new IllegalArgumentException("Order not found")). A missing order is an error, so the code should stop with a clear message rather than carry on with a made-up default.