Sub topic 5
Getting the Value Out Safely
An Optional is useful only if you can get the value back out of it. This chapter covers the methods that do that: get, orElse, orElseGet, and orElseThrow. Each one handles the empty case differently. By the end, you will know which method to use and why get is usually the wrong pick.
In the last chapter you learned to check for a value with isPresent and isEmpty. The methods here combine the check and the retrieval in one step, which makes your code shorter and less likely to break.
The Four Ways to Get a Value
Every retrieval method asks the same question: "What should happen if the box is empty?" Here is a quick overview before we look at each one.
| Method | If a value is present | If the Optional is empty |
|---|---|---|
| `get()` | Returns the value | Throws `NoSuchElementException` |
| `orElse(default)` | Returns the value | Returns `default` |
| `orElseGet(supplier)` | Returns the value | Calls `supplier` and returns its result |
| `orElseThrow(supplier)` | Returns the value | Throws the exception that `supplier` makes |
| `orElseThrow()` (Java 10+) | Returns the value | Throws `NoSuchElementException` |
When a value is present, all of these methods behave the same way. They differ only in how they handle "nothing here."
get: The Risky One
get() returns the value inside the Optional. If the Optional is empty, it throws an exception. An exception is an error object that Java "throws" to stop normal code when something goes wrong. In this case it is a NoSuchElementException.
import java.util.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();
try {
empty.get();
} catch (NoSuchElementException e) {
System.out.println("Error: " + e.getMessage()); // Error: No value present
}
}
}So get looks easy, but it has the same weakness as null. If you forget to check first, your program crashes. You swapped a NullPointerException for a NoSuchElementException, and you gained nothing.
Some people write this pattern to stay safe:
import java.util.Optional;
public class CheckThenGet {
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
String result;
if (name.isPresent()) {
result = name.get();
} else {
result = "Guest";
}
System.out.println(result); // Ada
}
}This code works, but it is just a null check written in a longer way. The methods below do the same job in one line.
orElse: A Ready-Made Default
orElse takes a default value. A default value is the value you use when the real one is missing. If the Optional has a value, you get that value. If it is empty, you get the default.
import java.util.Optional;
public class OrElseDemo {
public static void main(String[] args) {
Optional<String> nickname = Optional.empty();
Optional<String> realName = Optional.of("Grace");
System.out.println(nickname.orElse("Guest")); // Guest
System.out.println(realName.orElse("Guest")); // Grace
}
}The result is a plain String, not an Optional<String>. After orElse, you are back to an ordinary value that you can use anywhere.
Use orElse when the default is simple and already known, such as a fixed text, a number, or an empty list.
Edge case: orElse(null)
You can pass null to orElse:
import java.util.Optional;
public class OrElseNullDemo {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
String value = empty.orElse(null);
System.out.println(value == null); // true
}
}This is allowed. It is mostly useful when you pass a value to older code that expects null for "nothing." Avoid it in new code, because it brings back the problem Optional was made to solve.
orElseGet: A Default Made on Demand
orElseGet also gives a default, but you hand it a Supplier instead of a value. A Supplier is a small piece of code, usually a lambda like () -> "text", that produces a value when called. orElseGet calls the Supplier only when the Optional is empty.
import java.util.Optional;
public class OrElseGetDemo {
static String buildDefault() {
System.out.println("Building default...");
return "Computed default";
}
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
Optional<String> full = Optional.of("Real value");
System.out.println(empty.orElseGet(OrElseGetDemo::buildDefault));
// Building default...
// Computed default
System.out.println(full.orElseGet(OrElseGetDemo::buildDefault));
// Real value (buildDefault is never called)
}
}In the second call, "Building default..." does not print, because the Optional already had a value.
Use orElseGet when making the default takes work, for example reading a file, calling a database, or creating a large object. A later chapter, "orElse vs orElseGet: When Defaults Are Computed," looks at this difference closely.
Edge case: a Supplier that returns null
If your Supplier returns null, orElseGet returns null too. It does not protect you from your own Supplier. Make sure the Supplier always gives back a real value.
orElseThrow: When Missing Means Error
Sometimes there is no sensible default. If a user asks for order number 42 and it does not exist, inventing a fake order would be wrong. The right response is a clear error.
orElseThrow takes a Supplier that creates an exception. If the Optional is empty, Java throws that exception.
import java.util.Optional;
public class OrElseThrowDemo {
public static void main(String[] args) {
Optional<String> city = Optional.empty();
try {
String c = city.orElseThrow(() -> new IllegalStateException("No city"));
System.out.println(c);
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No city
}
}
}The benefit over get is the message. "No value present" tells you nothing. "No city" or "Order 42 not found" tells you exactly what went wrong.
The no-argument version (Java 10+)
Java 10 added orElseThrow() with no arguments. It works exactly like get() and throws NoSuchElementException. The only change is the name. Because orElseThrow clearly says "this may throw," many teams prefer it to get.
import java.util.NoSuchElementException;
import java.util.Optional;
public class OrElseThrowNoArg {
public static void main(String[] args) {
Optional<Integer> score = Optional.of(97);
System.out.println(score.orElseThrow()); // 97
try {
Optional.<Integer>empty().orElseThrow();
} catch (NoSuchElementException e) {
System.out.println("Caught: " + e.getMessage()); // Caught: No value present
}
}
}Edge case: checked exceptions
A checked exception is one that Java forces you to handle or declare with throws, such as IOException. If your Supplier creates a checked exception, the method that calls orElseThrow must declare it:
import java.io.IOException;
import java.util.Optional;
public class CheckedDemo {
static String loadPath(Optional<String> path) throws IOException {
return path.orElseThrow(() -> new IOException("No file path given"));
}
public static void main(String[] args) {
try {
System.out.println(loadPath(Optional.of("data.txt"))); // data.txt
System.out.println(loadPath(Optional.empty()));
} catch (IOException e) {
System.out.println(e.getMessage()); // No file path given
}
}
}If you leave out throws IOException, the code will not compile.
Worked Example: Reading Settings
Let's put the methods together. An app reads settings from a map. Some settings have good defaults. One setting, the API key, is required, and the app can't run without it.
import java.util.Map;
import java.util.Optional;
public class SettingsDemo {
static final Map<String, String> SETTINGS = Map.of("host", "localhost");
static Optional<String> setting(String key) {
return Optional.ofNullable(SETTINGS.get(key));
}
static String defaultTheme() {
System.out.println("(looking up system theme)");
return "light";
}
public static void main(String[] args) {
String host = setting("host").orElse("127.0.0.1");
String port = setting("port").orElse("8080");
System.out.println(host + ":" + port); // localhost:8080
String theme = setting("theme").orElseGet(SettingsDemo::defaultTheme);
System.out.println("Theme: " + theme);
// (looking up system theme)
// Theme: light
try {
String apiKey = setting("apiKey")
.orElseThrow(() -> new IllegalStateException("Missing setting: apiKey"));
System.out.println("Key: " + apiKey);
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // Missing setting: apiKey
}
}
}Here is what each line does:
hostexists in the map, soorElsereturns"localhost".portis missing, soorElsereturns the fixed default"8080".themeis missing. The default takes work to find, soorElseGetrunsdefaultThemeonly now.apiKeyis missing and required, soorElseThrowstops with a message that names the missing setting.
Each line states its own rule for the empty case. A reader can see the rule without hunting for an if statement.
Common Mistakes
- Calling
get()without a check. This crashes on an empty Optional. UseorElse,orElseGet, ororElseThrow. - Writing
isPresent()thenget(). It works but adds lines for no benefit. OneorElsecall does the same thing. - Using
orElsewith costly work. Code likeorElse(loadFromDatabase())runs the database call every time, even when a value is present. UseorElseGetinstead. - Vague exceptions.
orElseThrow()with no message makes bugs harder to find. When the cause matters, pass a Supplier that builds an exception with a clear message.
Exercise
What does this code print, and why? Optional<String> o = Optional.of("Sam"); System.out.println(o.orElse("Guest") + " " + Optional.<String>empty().orElse("Guest"));
Show answer
It prints "Sam Guest". The first Optional holds "Sam", so orElse returns it and ignores the default. The second Optional is empty, so orElse returns the default "Guest".
Exercise
A method findUser(id) returns Optional<User>. A missing user is a bug in your program, and you want the error message "User 7 not found". Write one line that gets the user for id 7.
Show answer
User user = findUser(7).orElseThrow(() -> new IllegalStateException("User 7 not found")); This returns the user when present and throws an exception with a clear message when it is empty. Any unchecked exception type that fits your program, such as NoSuchElementException, also works.
Exercise
Why is orElseThrow() with no arguments (Java 10+) often preferred over get(), even though both throw NoSuchElementException?
Show answer
They behave the same, but the name orElseThrow tells the reader that the call can throw when the Optional is empty. The name get hides that risk and looks like a safe call, so mistakes with it are easier to miss.