Careeroza
Why Optional
The Null Problem
Returning null to mean "not found" forces every caller to remember a null check. Forget it once and you get a NullPointerException in production. Optional<T> is a box that is either empty or holds one value, so the "might be missing" fact is part of the method signature.
Example
The null version crashes when the user is missing.
import java.util.*;
public class Main {
static Map<Integer, String> users = Map.of(1, "Ravi", 2, "Anita");
static String findName(int id) { return users.get(id); } // may return null
public static void main(String[] args) {
System.out.println(findName(1).toUpperCase());
System.out.println(findName(3).toUpperCase());
}
}Output
RAVI Exception: java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because the return value of "Main.findName(int)" is null
The Optional Version
Example
The caller is forced to decide what happens when the value is missing.
import java.util.*;
public class Main {
static Map<Integer, String> users = Map.of(1, "Ravi", 2, "Anita");
static Optional<String> findName(int id) { return Optional.ofNullable(users.get(id)); }
public static void main(String[] args) {
System.out.println(findName(1).map(String::toUpperCase).orElse("GUEST"));
System.out.println(findName(3).map(String::toUpperCase).orElse("GUEST"));
}
}Output
RAVI GUEST