Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Optional: "Maybe a Value" Without null

    Optional<T> is a container that holds either one value or nothing. It's designed as a return type for methods that might not find a

    Chapter 8 of 113 min read

    The Plain Picture#

    A gift box that might be empty. You can check whether there's something inside, take it out, or say "if it's empty, give me this instead" — but you never get a nasty surprise from opening a box that wasn't there at all.

    The Real Names#

    • Optional<T> is a container that holds either one value or nothing. It's designed as a return type for methods that might not find a result, making "no result" impossible to forget — unlike returning null (Classes, Objects and Memory Ch 4).

    • Create: Optional.of(x) (x must not be null), Optional.ofNullable(x) (null → empty), Optional.empty().

    • Stream methods like findFirst, min, max return Optional.

    Under the Hood#

    Java
    static Optional<Student> findByName(List<Student> all, String name) {
        return all.stream().filter(s -> s.name().equals(name)).findFirst();
    }
    
    findByName(students, "Aisha").map(Student::score).orElse(0)     // 200
    findByName(students, "Zoya").map(Student::score).orElse(0)      // 0      — no null anywhere
    findByName(students, "Zoya").isPresent()                        // false
    findByName(students, "Zoya").orElseThrow()                      // NoSuchElementException: No value present

    The methods: isPresent(), isEmpty(), ifPresent(consumer), map(f) (transform if present), flatMap(f) (when f itself returns an Optional), filter(p), orElse(default), orElseGet(supplier), orElseThrow() / orElseThrow(() -> new NotFoundException(...)).

    The orElse vs orElseGet trap#

    Java
    static String expensive() {
        System.out.println("  (expensive default computed)");
        return "default";
    }
    
    Optional.of("real").orElse(expensive()); // prints "(expensive default computed)" — even though a value exists!
    
    Optional.of("real").orElseGet(Modern::expensive); // prints nothing

    orElse(x) is a normal method call, so its argument is evaluated first, always. orElseGet(supplier) only calls the supplier if the Optional is empty. Use orElse for constants, orElseGet for anything costly (a database call, building an object).

    How to use Optional well#

    • ✅ as a method return type when "no result" is normal: Optional<User> findByEmail(String email).

    • ❌ not for fields, method parameters, or collections (return an empty list, not Optional<List<...>>).

    • ❌ never call .get() without checking — that's a NullPointerException with extra steps. Prefer map/orElse/orElseThrow.

    • ❌ never return null from a method whose return type is Optional.

    Check yourself

    4 questions
    1

    What problem does Optional solve?

    Show answer

    It makes "no result" explicit in the return type, so callers can't forget to handle it the way they forget null checks.

    2

    orElse vs orElseGet?

    Show answer

    orElse's argument is always evaluated; orElseGet only computes the default when the Optional is empty.

    3

    Where should you not use Optional?

    Show answer

    Fields, method parameters, and wrapping collections.

    4

    Rewrite without null checks: Student s = find(name); int score = (s == null) ? 0 : s.score();

    Show answer

    int score = find(name).map(Student::score).orElse(0); (with find returning Optional<Student>).