Optional
Creating and Checking an Optional
Creating Optionals
import java.util.Optional;
Optional<String> present = Optional.of("hello");
Optional<String> absent = Optional.empty();
Optional<String> maybeNull = Optional.ofNullable(null); // safe even if the value is null
System.out.println(present.isPresent()); // true
System.out.println(absent.isEmpty()); // true (Java 11+)true true
orElse(), orElseGet(), orElseThrow(), ifPresent()
Instead of unwrapping an Optional with a manual if-check, Optional's real value comes from methods that describe what to do in the absent case declaratively.
Handling absence without an explicit if-check
import java.util.Optional;
public class OptionalDemo {
static String computeDefaultName() {
return "anonymous";
}
public static void main(String[] args) {
Optional<String> username = Optional.empty();
// orElse: a plain fallback value
System.out.println(username.orElse("guest"));
// orElseGet: a fallback computed lazily (only runs if empty)
System.out.println(username.orElseGet(OptionalDemo::computeDefaultName));
// ifPresent: run code only when a value exists
Optional.of("Nadia").ifPresent(name -> System.out.println("Hello, " + name));
// orElseThrow: fail loudly with a meaningful exception if absent
try {
username.orElseThrow(() -> new IllegalStateException("No user logged in"));
} catch (IllegalStateException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}guest anonymous Hello, Nadia Caught: No user logged in
Chaining with map() and filter()
Chaining map() and filter()
import java.util.Optional;
Optional<String> email = Optional.of(" ADA@EXAMPLE.COM ");
String normalized = email
.map(String::trim)
.map(String::toLowerCase)
.filter(e -> e.contains("@"))
.orElse("invalid-email");
System.out.println(normalized);
Optional<String> blank = Optional.of("not-an-email");
System.out.println(
blank.filter(e -> e.contains("@")).orElse("invalid-email")
);ada@example.com invalid-email
Method | Behavior |
|---|---|
isPresent()/isEmpty() | Check whether a value exists (isEmpty() since Java 11) |
get() | Returns the value or throws — avoid calling directly |
orElse(value) | Fallback value, always evaluated |
orElseGet(supplier) | Fallback computed lazily, only if empty |
orElseThrow(supplier) | Throws a custom exception if empty |
ifPresent(consumer) | Runs code only when a value is present |
map()/filter() | Transform or conditionally clear the value, staying inside Optional |
Optional<T> represents a result that may or may not be present
Use it as a return type — not for fields or method parameters
Avoid calling get() directly; prefer orElse()/orElseGet()/orElseThrow()/ifPresent()
map() and filter() let you build null-check-free transformation pipelines