Optional and the null problem

Java 8 Course · lesson 7 of 16 · 4 min read

Why a wrapper type was added, and the narrow job it was actually designed for.

Open this lesson in the learning hub

Key points

  • A method returning null tells the caller nothing - they find out at the next dot, in production.
  • Optional moves "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.
  • orElse evaluates its argument even when a value is present; orElseGet takes 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.