Java Optional Class
The Problem Optional Solves
Many methods sometimes have no result: a user lookup finds nobody, a search finds no match, a configuration key isn't set. Traditionally, Java methods return null in that case. The trouble is that nothing in the method's signature says so:
String email = findEmail("ravi"); // might be null — the type String doesn't tell you
email.toUpperCase(); // NullPointerException if it was
Callers forget to check, and the program fails with a NullPointerException somewhere far from the cause. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake".
java.util.Optional<T> (Java 8) is a container that holds either one value or nothing. A method that returns Optional<String> states in its signature that the result may be absent, and the Optional API makes the caller decide what to do in that case — use a default, throw an exception, skip an action — before getting at the value.
Optional<String> email = findEmail("ravi");
String address = email.orElse("no email"); // the absent case is handled explicitly
Creating and Reading Optionals
import java.util.*;
public class O1 {
static final Map<String, String> EMAILS = Map.of("asha", "asha@gocourse.in");
static Optional<String> findEmail(String user) {
return Optional.ofNullable(EMAILS.get(user));
}
public static void main(String[] args) {
Optional<String> a = Optional.of("Java");
Optional<String> b = Optional.empty();
Optional<String> c = Optional.ofNullable(null);
System.out.println(a + " " + b + " " + c + " " + b.equals(c));
try {
Optional.of(null);
} catch (NullPointerException e) {
System.out.println("Optional.of(null): NullPointerException");
}
System.out.println(findEmail("asha").isPresent() + " " + findEmail("ravi").isEmpty());
System.out.println(findEmail("asha").orElse("no email"));
System.out.println(findEmail("ravi").orElse("no email"));
try {
findEmail("ravi").get();
} catch (NoSuchElementException e) {
System.out.println("get() on empty: NoSuchElementException " + e.getMessage());
}
try {
findEmail("ravi").orElseThrow(() -> new IllegalArgumentException("user ravi has no email"));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
findEmail("asha").ifPresent(e -> System.out.println("sending to " + e));
findEmail("ravi").ifPresentOrElse(e -> System.out.println("sending to " + e),
() -> System.out.println("ravi: ask for an email first"));
}
}
Output:
Optional[Java] Optional.empty Optional.empty true
Optional.of(null): NullPointerException
true true
asha@gocourse.in
no email
get() on empty: NoSuchElementException No value present
user ravi has no email
sending to asha@gocourse.in
ravi: ask for an email first
Creating
| Method | Use when |
|---|---|
Optional.of(value) | The value is definitely not null — throws NullPointerException otherwise |
Optional.ofNullable(value) | The value may be null — gives an empty Optional for null |
Optional.empty() | There is no value |
findEmail uses ofNullable because Map.get returns null for missing keys — this is the typical bridge from older, null-returning APIs.
Checking and getting the value
| Method | Behaviour |
|---|---|
isPresent() / isEmpty() (Java 11+) | Whether a value is there |
orElse(default) | The value, or the default |
orElseGet(supplier) | The value, or a default computed only if needed |
orElseThrow(exceptionSupplier) | The value, or throw your exception |
orElseThrow() (Java 10+) | The value, or throw NoSuchElementException |
get() | Same as orElseThrow() — avoid it (see below) |
ifPresent(consumer) | Run an action only if there's a value |
ifPresentOrElse(consumer, runnable) (Java 9+) | One action for a value, another for absence |
Avoid get(): optional.get() throws NoSuchElementException for an empty Optional, which is just a NullPointerException under another name. Code like if (opt.isPresent()) { use(opt.get()); } is legal but gains nothing over a null check. The methods that combine the check and the access — orElse, orElseThrow, ifPresent, map — express the intent directly. When you're certain a value exists, orElseThrow() says so explicitly.
orElse versus orElseGet
import java.util.*;
public class Lazy {
static String expensiveDefault() {
System.out.println(" (computing default...)");
return "guest";
}
public static void main(String[] args) {
Optional<String> name = Optional.of("asha");
System.out.println("orElse: " + name.orElse(expensiveDefault()));
System.out.println("orElseGet: " + name.orElseGet(Lazy::expensiveDefault));
System.out.println("empty orElseGet: " + Optional.<String>empty().orElseGet(Lazy::expensiveDefault));
}
}
Output:
(computing default...)
orElse: asha
orElseGet: asha
(computing default...)
empty orElseGet: guest
orElse(expensiveDefault()) is an ordinary method call: Java evaluates the argument before calling orElse, so the default is computed even though a value is present. orElseGet(supplier) only calls the supplier when the Optional is empty. Use orElse for constants and cheap values; use orElseGet when the default involves work — a database query, a remote call, creating a large object — or has side effects.
Transforming: map, flatMap and filter
Optional has map, flatMap and filter, which work like their stream counterparts on a "stream" of zero or one elements. They let you chain steps where any step may produce nothing, without nested null checks.
import java.util.*;
public class Chain {
record Address(String street, String city, String pin) { }
record Customer(String name, Address address, String phone) {
Optional<Address> findAddress() { return Optional.ofNullable(address); }
}
static final Map<Integer, Customer> DB = Map.of(
1, new Customer("Asha", new Address("12 Anna Salai", "Chennai", "600002"), "+91-90000-11111"),
2, new Customer("Ravi", null, null),
3, new Customer("Meena", new Address("4 Gandhi Rd", "madurai", "625001"), " "));
static Optional<Customer> find(int id) { return Optional.ofNullable(DB.get(id)); }
static String deliveryCity(int id) {
return find(id)
.flatMap(Customer::findAddress)
.map(Address::city)
.map(c -> c.substring(0, 1).toUpperCase() + c.substring(1))
.orElse("(no address)");
}
static Optional<String> contactPhone(int id) {
return find(id).map(Customer::phone).filter(p -> !p.isBlank());
}
public static void main(String[] args) {
for (int id : new int[] {1, 2, 3, 4}) {
System.out.printf("%d: city=%s, phone=%s%n", id, deliveryCity(id), contactPhone(id).orElse("-"));
}
System.out.println(find(1).map(Customer::findAddress));
System.out.println(find(1).flatMap(Customer::findAddress).map(Address::pin));
}
}
Output:
1: city=Chennai, phone=+91-90000-11111
2: city=(no address), phone=-
3: city=Madurai, phone=-
4: city=(no address), phone=-
Optional[Optional[Address[street=12 Anna Salai, city=Chennai, pin=600002]]]
Optional[600002]
| Method | If a value is present | If empty |
|---|---|---|
map(f) | Applies f; returns Optional.ofNullable(result) | Stays empty |
flatMap(f) | Applies f, which itself returns an Optional; returns that | Stays empty |
filter(p) | Keeps the value if p is true, otherwise becomes empty | Stays empty |
or(supplier) (Java 9+) | Keeps this Optional | Returns the Optional from the supplier |
stream() (Java 9+) | A one-element stream | An empty stream |
How the lookups work:
deliveryCitychains four steps, each of which may come up empty: customer 4 doesn't exist, customer 2 has no address. WithoutOptionalthis would be three nestedif (x != null)checks. Only at the end is the absence handled, withorElse.mapversusflatMap:findAddressalready returns anOptional<Address>. Withmap, the result is wrapped a second time —Optional[Optional[Address[...]]], as the last-but-one line shows.flatMaptakes the innerOptionalas the result. Rule: usemapwhen the function returns a plain value,flatMapwhen it returns anOptional.mapturnsnullinto empty: Ravi's phone isnull;map(Customer::phone)produces an emptyOptionalrather than anOptionalcontainingnull.filtertreats a blank phone number (Meena's" ") as absent.
Primitive Optionals
OptionalInt, OptionalLong and OptionalDouble hold primitive values without boxing. They're returned by primitive stream operations such as IntStream.max(), average() and findFirst(), and read with getAsInt(), orElse(...), orElseThrow(). They have fewer methods than Optional — no map, flatMap or filter.
Guidelines for Using Optional
Optional was designed for one main purpose: method return values that may be absent. Using it everywhere causes more problems than it solves.
| Do | Don't |
|---|---|
Return Optional<T> from methods that may find nothing (findById, findFirst, lookups) | Use Optional as a field type — it isn't Serializable, and a nullable field with an accessor returning Optional (like findAddress above) is the usual pattern |
Handle absence with orElse, orElseGet, orElseThrow, map, ifPresent | Call get() without being sure there's a value |
| Return an empty collection when there are no results | Return Optional<List<T>> — an empty list already means "none" |
| Accept plain parameters and overload or use defaults | Use Optional as a method parameter — callers then have to wrap values, and can still pass null |
Return Optional.empty() | Return null from a method declared to return Optional — that defeats the whole point |
Also avoid Optional in performance-critical inner loops (each one is an extra object), and don't use it as a general replacement for every null check inside a method — a simple if is often clearer locally. The value of Optional is in APIs, where it communicates "this might be missing" to every caller.
Practical Example: Layered Configuration Lookup
Applications read settings from several places in order of priority — environment variables override a configuration file, which overrides built-in defaults. Each source may or may not contain a key, and blank values should count as "not set". Optional expresses "try this source, otherwise the next" directly.
import java.time.Duration;
import java.util.*;
import java.util.stream.*;
public class Cfg {
record Source(String name, Map<String, String> values) {
Optional<String> get(String key) {
return Optional.ofNullable(values.get(key)).map(String::strip).filter(v -> !v.isEmpty());
}
}
private final List<Source> sources;
Cfg(Source... sources) { this.sources = List.of(sources); }
Optional<String> lookup(String key) {
return sources.stream().map(s -> s.get(key)).flatMap(Optional::stream).findFirst();
}
Optional<String> lookupWithOr(String key) {
Source env = sources.get(0), file = sources.get(1), defaults = sources.get(2);
return env.get(key).or(() -> file.get(key)).or(() -> defaults.get(key));
}
int intValue(String key) {
return lookup(key).map(Integer::parseInt)
.orElseThrow(() -> new IllegalStateException("missing required setting: " + key));
}
public static void main(String[] args) {
Cfg cfg = new Cfg(
new Source("env", Map.of("PORT", "9090", "DB_URL", " ")),
new Source("file", Map.of("DB_URL", "jdbc:postgresql://db/shop", "TIMEOUT", "PT45S")),
new Source("defaults", Map.of("PORT", "8080", "TIMEOUT", "PT30S", "MAX_USERS", "100")));
System.out.println("PORT = " + cfg.intValue("PORT"));
System.out.println("DB_URL = " + cfg.lookup("DB_URL").orElse("-"));
System.out.println("TIMEOUT = " + cfg.lookup("TIMEOUT").map(Duration::parse).map(Duration::toSeconds).orElse(0L) + "s");
System.out.println("MAX_USERS = " + cfg.lookupWithOr("MAX_USERS").orElse("-"));
System.out.println("CACHE = " + cfg.lookup("CACHE").orElse("(not set)"));
try {
cfg.intValue("SMTP_PORT");
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
OptionalInt firstEven = IntStream.of(3, 5, 8, 10).filter(n -> n % 2 == 0).findFirst();
System.out.println(firstEven + " " + firstEven.getAsInt());
}
}
Output:
PORT = 9090
DB_URL = jdbc:postgresql://db/shop
TIMEOUT = 45s
MAX_USERS = 100
CACHE = (not set)
missing required setting: SMTP_PORT
OptionalInt[8] 8
How it works:
Source.getturns a raw map value into anOptional:ofNullablehandles missing keys,map(String::strip)trims whitespace, andfiltertreats an empty result as absent. That's why the blankDB_URLin the environment doesn't override the file's value.lookupstreams the sources in priority order, maps each to itsOptionalvalue, keeps only present values withflatMap(Optional::stream), and takes the first. The stream is lazy, so lower-priority sources aren't consulted once a value is found.lookupWithOrexpresses the same fallback chain withOptional.or(Java 9+): each supplier runs only if everything before it was empty. It's convenient when there's a small, fixed number of sources.- Typed access:
intValueconverts withmap(Integer::parseInt)and throws a clear exception for required settings that are missing, instead of failing later with aNullPointerException.TIMEOUTis converted from an ISO-8601 duration with twomapsteps. - Optional settings use
orElseto describe the absence (CACHE); required ones useorElseThrow(SMTP_PORT). OptionalIntappears naturally as the result offindFirst()on anIntStream.
Frameworks such as Spring Boot and MicroProfile Config resolve properties from layered sources by priority in the same way; MicroProfile Config, for example, offers getOptionalValue(name, type) for settings that may not be set.