Optional in Java 8
Optional<T> is a container that either holds a value or is empty. Added in Java 8, it lets a method say clearly in its return type that a result may be missing, instead of returning null.
This tutorial shows how to create and read an Optional, how to chain operations safely, and where Optional should and should not be used.
1. Why Is Optional Needed?
A method that returns null for "not found" relies on every caller remembering to check. When someone forgets, the result is a NullPointerException far from the real cause. Optional makes the possibility of absence visible in the type and provides methods to handle it explicitly.
2. Creating and Reading an Optional
| Method | Purpose |
|---|---|
Optional.of(value) | wraps a non-null value; throws NullPointerException for null |
Optional.ofNullable(value) | empty if the value is null |
Optional.empty() | an empty Optional |
orElse(default) | value or a default that is always evaluated |
orElseGet(supplier) | value or a default computed only when needed |
orElseThrow(supplier) | value or a custom exception |
map, flatMap, filter | transform or test the value if present |
ifPresent(consumer) | run code only when a value exists |
3. Practical Examples
Example 1: Returning Optional from a lookup
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class OptionalBasics {
static final Map<String, String> PHONE_BOOK = new HashMap<>();
static {
PHONE_BOOK.put("asha", "98450 11111");
}
// The return type tells callers that a phone number may be missing
static Optional<String> findPhone(String user) {
return Optional.ofNullable(PHONE_BOOK.get(user));
}
public static void main(String[] args) {
Optional<String> found = findPhone("asha");
Optional<String> missing = findPhone("ravi");
System.out.println("isPresent : " + found.isPresent() + ", " + missing.isPresent());
System.out.println("orElse : " + missing.orElse("not listed"));
System.out.println("map : " + found.map(p -> p.replace(" ", "")).orElse("-"));
found.ifPresent(p -> System.out.println("ifPresent : call " + p));
// orElseGet runs the supplier only when the value is missing
String fallback = missing.orElseGet(() -> "helpdesk 1800-000");
System.out.println("orElseGet : " + fallback);
try {
missing.orElseThrow(() -> new IllegalArgumentException("no phone for ravi"));
} catch (IllegalArgumentException e) {
System.out.println("orElseThrow: " + e.getMessage());
}
}
}
isPresent : true, false orElse : not listed map : 9845011111 ifPresent : call 98450 11111 orElseGet : helpdesk 1800-000 orElseThrow: no phone for ravi
The caller decides what an absent value means: a default text, a computed fallback, or an exception.
Example 2: Replacing nested null checks
The old method needs a chain of != null tests. The Optional chain says the same thing step by step, and every step is skipped automatically once the value is missing.
import java.util.Optional;
public class OptionalChaining {
static class Address {
final String city;
Address(String city) { this.city = city; }
}
static class Customer {
final Address address; // may be null
Customer(Address address) { this.address = address; }
}
// Before Java 8: nested null checks
static String cityOld(Customer c) {
if (c != null && c.address != null && c.address.city != null) {
return c.address.city.toUpperCase();
}
return "UNKNOWN";
}
// Java 8: the same rule as an Optional chain
static String cityNew(Customer c) {
return Optional.ofNullable(c)
.map(x -> x.address)
.map(a -> a.city)
.filter(city -> !city.isEmpty())
.map(String::toUpperCase)
.orElse("UNKNOWN");
}
public static void main(String[] args) {
Customer[] customers = { new Customer(new Address("mysuru")), new Customer(null), null };
for (Customer c : customers) {
System.out.println(cityOld(c) + " | " + cityNew(c));
}
}
}
MYSURU | MYSURU UNKNOWN | UNKNOWN UNKNOWN | UNKNOWN
4. How an Optional Chain Behaves
5. Important Points and Best Practices
- Use
Optionalmainly as a return type for methods that may not find a result. - Do not use it for fields, method parameters or collections; return an empty collection instead of
Optional<List>. - Never return
nullfrom a method declared to returnOptional. - Prefer
orElseGetoverorElsewhen the default is expensive to build. - Avoid calling
get()without checking; Java 10 addedorElseThrow()without arguments as a clearer alternative.
6. Summary
Optionalrepresents a value that may be absent and was added in Java 8.- Create it with
of,ofNullableorempty. - Read it with
orElse,orElseGet,orElseThroworifPresent. mapandfilterchains replace nested null checks.- Use it for return values, not for fields or parameters.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is Optional in Java?
A container class introduced in Java 8 that either holds a non-null value or is empty. It makes the possibility of a missing value explicit in a method's return type.
Q2. What is the difference between orElse and orElseGet?
orElse(value) always evaluates its argument, even when the Optional has a value. orElseGet(supplier) calls the supplier only when the Optional is empty, so it is better for expensive defaults.
Q3. What is the difference between Optional.of and Optional.ofNullable?
of requires a non-null value and throws NullPointerException otherwise. ofNullable returns an empty Optional for null.
Q4. Should Optional be used as a field or parameter?
No. It was designed as a return type. For fields, a nullable reference is simpler; for parameters, overloads or default values are clearer.