Lesson 8 of 10
Optional - Eliminating NullPointerException
Optional<T> is a container that may or may not hold a value. It makes the possibility of absence explicit in your API - forcing callers to handle the 'not found' case. NullPointerException is one of Java's most common runtime errors; Optional prevents it at the API boundary.
Optional - Creation & Use
import java.util.Optional;
import java.util.List;
public class OptionalDemo {
private static final List<String> books = List.of("Clean Code", "Effective Java", "DDIA");
// Return Optional instead of null when value might be absent
public static Optional<String> findByTitle(String query) {
return books.stream()
.filter(t -> t.equalsIgnoreCase(query))
.findFirst(); // returns Optional<String>
}
public static void main(String[] args) {
// Creating Optionals
Optional<String> filled = Optional.of("Hello"); // throws NPE if null
Optional<String> nullable = Optional.ofNullable(null); // wraps possibly-null value
Optional<String> empty = Optional.empty(); // explicitly empty
// ── Usage patterns ────────────────────────────────
Optional<String> result = findByTitle("clean code");
// 1. isPresent / isEmpty (least idiomatic - avoid when possible)
if (result.isPresent()) {
System.out.println("Found: " + result.get()); // get() throws if empty!
}
// 2. orElse - provide a default value
String title = findByTitle("Haskell").orElse("Not Found");
System.out.println(title); // Not Found
// 3. orElseGet - lazy default (computed only if empty)
String fetched = findByTitle("GoLang").orElseGet(() -> "Loading from DB...");
// 4. orElseThrow - throw if absent (most common in service/repository)
String found = findByTitle("Effective Java")
.orElseThrow(() -> new RuntimeException("Book not found"));
// 5. map - transform value if present
Optional<Integer> titleLength = findByTitle("Clean Code")
.map(String::length);
System.out.println(titleLength.orElse(0)); // 10
// 6. filter - keep value only if condition holds
Optional<String> longTitle = findByTitle("Clean Code")
.filter(t -> t.length() > 5);
// 7. ifPresent / ifPresentOrElse
findByTitle("DDIA").ifPresentOrElse(
t -> System.out.println("Found: " + t),
() -> System.out.println("Not in catalog")
);
// ── Anti-patterns ────────────────────────────────
// ❌ Never call get() without isPresent check
// ❌ Don't use Optional as a field type - use null or sentinel
// ❌ Don't use Optional<List> - return empty list instead
// ❌ Don't use Optional in constructor/method parameters - use overloads
}
}Quick Quiz
Tip
Tip
Practice Optional Eliminating NullPointerException in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Optional - Eliminating NullPointerException
Practice Task
Note
Practice Task - (1) Write a working example of Optional Eliminating NullPointerException from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Optional Eliminating NullPointerException is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?