Optional and the null problem
Why a wrapper type was added, and the narrow job it was actually designed for.
Open this lesson in the learning hubKey points
- A method returning
nulltells the caller nothing - they find out at the next dot, in production. Optionalmoves "this might be absent" into the type, so the compiler makes you look.- It was designed for return types. Fields and parameters were explicitly not the goal.
orElseevaluates its argument even when a value is present;orElseGettakes a supplier and does not.- Never call
get()without checking - that is just a NullPointerException with extra steps.
Example
import java.util.*;
public class Main {
static Optional<String> findUser(String id) {
return "u1".equals(id) ? Optional.of("Ada") : Optional.empty();
}
static String expensiveDefault() {
System.out.println(" (expensive default computed)");
return "fallback";
}
public static void main(String[] args) {
System.out.println(findUser("u1").map(String::toUpperCase).orElse("unknown"));
System.out.println(findUser("zz").map(String::toUpperCase).orElse("unknown"));
System.out.println("orElse on a PRESENT value still runs the default:");
System.out.println(" " + findUser("u1").orElse(expensiveDefault()));
System.out.println("orElseGet does not:");
System.out.println(" " + findUser("u1").orElseGet(Main::expensiveDefault));
findUser("u1").ifPresent(u -> System.out.println("ifPresent: " + u));
}
}
Optional is a return type that forces the caller to handle absence - not a general null replacement.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.