Why Optional Exists
Understand the null problem and how Optional models the absence of a value safely.
Why Optional Exists
The Optional class models the possible absence of a value. It forces callers to explicitly handle the "no value" case, reducing NullPointerExceptions.
The null Problem
Returning null from methods to indicate "no value" is dangerous — callers may forget to check, causing NPEs deep in the call stack.
// Old way — null return invites NPE
static String findEmail(int userId) {
if (userId == 1) return "alice@example.com";
return null; // caller might forget to check!
}
String email = findEmail(99);
System.out.println(email.toUpperCase()); // NullPointerException!