The NullPointerException is the most common crash in Java programs. It often starts with a method that returns null to mean “nothing found”, and a caller who forgets to check. Optional, added in Java 8, makes “there may be no value” part of the method’s return type, so the caller cannot ignore it. This lesson shows how to create, check, transform and unwrap an Optional, and when not to use one.
In this lesson you will learn
- Returning
Optionalinstead ofnull Optional.of,ofNullableandemptyisPresent,ifPresentandifPresentOrElse- Defaults with
orElse,orElseGetandorElseThrow - Chaining with
mapandfilter
You should know lambda expressions and the basics of the Streams API.
Creating and Reading an Optional
import java.util.List;
import java.util.Optional;
public class Main {
record Student(String name, String email) {}
static final List<Student> STUDENTS = List.of(
new Student("Nusrat", "nusrat@example.com"),
new Student("Arif", null));
// Returns Optional instead of null when nothing is found
static Optional<Student> findByName(String name) {
return STUDENTS.stream().filter(s -> s.name().equals(name)).findFirst();
}
public static void main(String[] args) {
Optional<Student> found = findByName("Nusrat");
Optional<Student> missing = findByName("Zara");
System.out.println(found.isPresent() + " " + missing.isPresent() + " " + missing.isEmpty());
System.out.println(found.get().name()); // safe here: we know it is present
System.out.println(missing.map(Student::name).orElse("no such student"));
found.ifPresent(s -> System.out.println("Hello, " + s.name()));
missing.ifPresentOrElse(
s -> System.out.println("Hello, " + s.name()),
() -> System.out.println("Zara is not registered"));
// Wrapping a value that might be null
for (Student s : STUDENTS) {
String email = Optional.ofNullable(s.email()).orElse("(no email)");
System.out.println(s.name() + ": " + email);
}
}
}
Output
true false true
Nusrat
no such student
Hello, Nusrat
Zara is not registered
Nusrat: nusrat@example.com
Arif: (no email)
findByNamereturnsOptional<Student>. Anyone calling it can see from the type that the student may not exist.findFirst()on a stream already returns anOptional.isPresent()andisEmpty()tell you whether a value is inside.get()returns the value but throwsNoSuchElementExceptionif the box is empty. Use it only when you have just checked, or better, avoid it.map(Student::name).orElse("no such student")transforms the value if there is one and supplies a default if not, without anyifstatement.ifPresentruns code only when a value exists;ifPresentOrElsealso handles the empty case.Optional.ofNullable(x)wraps a value that might benull. Arif’s missing email became “(no email)”.Optional.of(x)is for values that are never null; it throws if given null.
Chaining and Choosing a Default
import java.util.Map;
import java.util.Optional;
public class Main {
static final Map<String, String> CITY_OF = Map.of("Karim", "Dhaka", "Rina", "khulna");
static final Map<String, Integer> POSTCODE = Map.of("DHAKA", 1000, "KHULNA", 9000);
static Optional<String> city(String person) {
return Optional.ofNullable(CITY_OF.get(person));
}
static int expensiveDefault() {
System.out.println(" (computing default...)");
return 0;
}
public static void main(String[] args) {
// Chain steps; any empty step makes the whole result empty
for (String p : new String[] {"Karim", "Rina", "Joya"}) {
int code = city(p)
.map(String::toUpperCase)
.map(POSTCODE::get)
.filter(c -> c >= 1000)
.orElse(-1);
System.out.println(p + " -> " + code);
}
// orElse always evaluates its argument; orElseGet only when needed
System.out.println("orElse:");
city("Karim").map(String::length).orElse(expensiveDefault());
System.out.println("orElseGet:");
city("Karim").map(String::length).orElseGet(() -> expensiveDefault());
try {
city("Joya").orElseThrow(() -> new IllegalArgumentException("Joya has no city"));
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output
Karim -> 1000
Rina -> 9000
Joya -> -1
orElse:
(computing default...)
orElseGet:
Error: Joya has no city
- Each
mapstep runs only if the previous step produced a value. Joya has no city, so every later step is skipped and the result is -1. No null checks were needed. map(POSTCODE::get)can itself returnnull;mapturns that into an emptyOptionalautomatically.filterkeeps the value only if it passes the test.orElse(expensiveDefault())computes the default every time, even when the value is present, which is why “(computing default…)” printed.orElseGettakes a function and calls it only when needed.orElseThrowturns a missing value into a clear exception of your choice.
Optional Methods
| Method | What it does |
|---|---|
Optional.of(v) / ofNullable(v) / empty() | Create an Optional |
isPresent() / isEmpty() | Check for a value |
ifPresent(action) | Run code if a value exists |
map(f) / flatMap(f) | Transform the value; flatMap when f returns an Optional |
filter(test) | Keep the value only if it passes |
orElse(v) / orElseGet(supplier) | Value or a default |
orElseThrow() | Value or an exception |
or(supplier) | Try another Optional if this one is empty |
Common Mistakes
- Calling
get()without checking, which just moves the crash. PreferorElse,mapororElseThrow. - Returning
nullfrom a method declared to returnOptional. ReturnOptional.empty(). - Using
Optionalfor fields, method parameters or collections. It was designed for return values; an empty list is better than anOptional<List>. - Writing
if (opt.isPresent()) { … opt.get() … }everywhere, which is just a null check with more typing.
Practice Exercises
Exercise 1. Write Optional<Integer> parse(String s) that returns the number, or an empty Optional if s is not a valid integer.
Show answer
static Optional<Integer> parse(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
// parse("42").orElse(0) is 42, parse("4x").orElse(0) is 0
Exercise 2. Using city() from the second example, print the length of a person’s city name, or “unknown”.
Show answer
String len = city("Rina").map(c -> String.valueOf(c.length())).orElse("unknown");
System.out.println(len); // 6
Frequently Asked Questions
Does Optional replace null completely?
No. It is meant for return values that may be missing. Inside a class, a private field that is sometimes null is still normal Java.
What are OptionalInt and OptionalDouble?
Versions for primitive values that avoid boxing. Streams of numbers return them, for example IntStream.max() returns an OptionalInt, read with getAsInt() or orElse.
Summary
Optionalmakes “maybe no value” visible in the return type.- Create with
of,ofNullableorempty. - Transform with
mapandfilter; finish withorElse,orElseGetororElseThrow. - Avoid bare
get(), and do not use Optional for fields or parameters.
Next: Java Date and Time API.
