Sir Tony Hoare famously called the invention of the null pointer his "billion-dollar mistake". In Java, NullPointerException (NPE) has historically been the #1 cause of production application crashes. java.util.Optional<T> provides an elegant, expressive container to eliminate null checks.
import java.util.Optional;
public class OptionalDemo {
// Method explicitly declares that a User might not exist!
public static Optional<String> findUserEmail(int userId) {
if (userId == 101) {
return Optional.of("aarav@veewom.com"); // Non-null container
}
return Optional.empty(); // Safe empty container (No null returned!)
}
public static void main(String[] args) {
Optional<String> userEmail = findUserEmail(101);
// 1. ifPresent() - Executes Consumer only if value exists
userEmail.ifPresent(email -> System.out.println("Sending alert to: " + email));
// 2. orElse() - Fallback default value
Optional<String> unknownEmail = findUserEmail(999);
String finalEmail = unknownEmail.orElse("support@veewom.com");
System.out.println("Target: " + finalEmail); // support@veewom.com
// 3. orElseThrow() - Throws custom business exception if absent
String verified = userEmail.orElseThrow(() -> new RuntimeException("User not found!"));
}
}
Now let us step into high-performance concurrency starting with Multithreading fundamentals: Thread vs Runnable. Proceed to: Java Multithreading →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Finding elements with Optional.
Suppliers in orElseGet().
Entering concurrency.
Throwing custom exceptions from Optional.