← Back to Home
Module 1 - Optionals
Module Overview
Learn about Java Optionals and how to handle null values effectively to write safer, more maintainable code.
This video introduces the concept of Optionals in Java as a solution to the common issues associated with null values. You'll learn why null references are problematic in Java applications and how the Optional class was designed to provide a more elegant alternative for representing the absence of a value.
This deep dive into Java Optionals covers practical examples of creating, using, and manipulating Optional objects. The video demonstrates common patterns and best practices that help you leverage Optionals effectively in your code to handle nullable values safely.
Learning Objectives
- Understand the purpose and benefits of using Optionals in Java
Optionals provide a type-level solution to represent the presence or absence of a value, helping to avoid NullPointerExceptions and making code more readable and expressive.
- Implement a method that returns an empty Optional when it has no result
When a method cannot produce a meaningful result, returning Optional.empty() is safer than returning null.
public Optional<User> findUserById(String id) {
// If user not found
return Optional.empty();
}
- Implement a method that wraps its return value in an Optional
Learn to use Optional.of() and Optional.ofNullable() to create Optional instances that may contain values.
public Optional<Product> findProduct(String sku) {
Product product = database.lookup(sku);
return Optional.ofNullable(product);
}
- Implement code to access the wrapped value of an Optional
Discover safe ways to extract values from Optionals using methods like get(), orElse(), orElseGet(), and orElseThrow().
Optional<String> optional = getOptionalValue();
// Safe access with default value
String value = optional.orElse("default");
// With supplier for lazy evaluation
String computed = optional.orElseGet(() -> computeDefault());
// Throwing custom exception if empty
String required = optional.orElseThrow(() ->
new IllegalStateException("Value must be present"));
- Explain the dangers of having a method return null
Returning null requires callers to remember null checks, leads to NullPointerExceptions, and creates ambiguity about whether null is a valid return value or indicates an error condition.
- Outline how to use the filter, map, and flatMap methods of the Optional class
These methods allow functional-style operations on Optional values, enabling powerful transformations and conditionals.
Optional<User> user = findUser(id);
// Filter: keeps value only if predicate is true
Optional<User> activeUser = user.filter(u -> u.isActive());
// Map: transforms the value if present
Optional<String> username = user.map(User::getUsername);
// FlatMap: for when the mapper returns an Optional
Optional<Address> address = user.flatMap(User::getAddress);
- Outline when Optionals shouldn't be used
Optionals aren't suitable for class fields, method parameters, or collections of optional elements. They should primarily be used as method return types when a value might be absent.