00:00

Optional in Java 8

Last updated: · Standard (Java 8)

Optional<T> is a container that either holds a value or is empty. Added in Java 8, it lets a method say clearly in its return type that a result may be missing, instead of returning null.

This tutorial shows how to create and read an Optional, how to chain operations safely, and where Optional should and should not be used.

1. Why Is Optional Needed?

A method that returns null for "not found" relies on every caller remembering to check. When someone forgets, the result is a NullPointerException far from the real cause. Optional makes the possibility of absence visible in the type and provides methods to handle it explicitly.

2. Creating and Reading an Optional

MethodPurpose
Optional.of(value)wraps a non-null value; throws NullPointerException for null
Optional.ofNullable(value)empty if the value is null
Optional.empty()an empty Optional
orElse(default)value or a default that is always evaluated
orElseGet(supplier)value or a default computed only when needed
orElseThrow(supplier)value or a custom exception
map, flatMap, filtertransform or test the value if present
ifPresent(consumer)run code only when a value exists

3. Practical Examples

Example 1: Returning Optional from a lookup

OptionalBasics.java
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class OptionalBasics {
    static final Map<String, String> PHONE_BOOK = new HashMap<>();

    static {
        PHONE_BOOK.put("asha", "98450 11111");
    }

    // The return type tells callers that a phone number may be missing
    static Optional<String> findPhone(String user) {
        return Optional.ofNullable(PHONE_BOOK.get(user));
    }

    public static void main(String[] args) {
        Optional<String> found = findPhone("asha");
        Optional<String> missing = findPhone("ravi");

        System.out.println("isPresent : " + found.isPresent() + ", " + missing.isPresent());
        System.out.println("orElse    : " + missing.orElse("not listed"));
        System.out.println("map       : " + found.map(p -> p.replace(" ", "")).orElse("-"));
        found.ifPresent(p -> System.out.println("ifPresent : call " + p));

        // orElseGet runs the supplier only when the value is missing
        String fallback = missing.orElseGet(() -> "helpdesk 1800-000");
        System.out.println("orElseGet : " + fallback);

        try {
            missing.orElseThrow(() -> new IllegalArgumentException("no phone for ravi"));
        } catch (IllegalArgumentException e) {
            System.out.println("orElseThrow: " + e.getMessage());
        }
    }
}
Output
isPresent : true, false
orElse    : not listed
map       : 9845011111
ifPresent : call 98450 11111
orElseGet : helpdesk 1800-000
orElseThrow: no phone for ravi

The caller decides what an absent value means: a default text, a computed fallback, or an exception.

Example 2: Replacing nested null checks

The old method needs a chain of != null tests. The Optional chain says the same thing step by step, and every step is skipped automatically once the value is missing.

OptionalChaining.java
import java.util.Optional;

public class OptionalChaining {
    static class Address {
        final String city;
        Address(String city) { this.city = city; }
    }

    static class Customer {
        final Address address;   // may be null
        Customer(Address address) { this.address = address; }
    }

    // Before Java 8: nested null checks
    static String cityOld(Customer c) {
        if (c != null && c.address != null && c.address.city != null) {
            return c.address.city.toUpperCase();
        }
        return "UNKNOWN";
    }

    // Java 8: the same rule as an Optional chain
    static String cityNew(Customer c) {
        return Optional.ofNullable(c)
                .map(x -> x.address)
                .map(a -> a.city)
                .filter(city -> !city.isEmpty())
                .map(String::toUpperCase)
                .orElse("UNKNOWN");
    }

    public static void main(String[] args) {
        Customer[] customers = { new Customer(new Address("mysuru")), new Customer(null), null };
        for (Customer c : customers) {
            System.out.println(cityOld(c) + " | " + cityNew(c));
        }
    }
}
Output
MYSURU | MYSURU
UNKNOWN | UNKNOWN
UNKNOWN | UNKNOWN

4. How an Optional Chain Behaves

An Optional chain stops at the first missing value A customer is wrapped with ofNullable, then map steps read the address and the city. If any step finds null, the chain becomes empty and orElse returns UNKNOWN. PRESENT ofNullable(customer) has value map(address) has value map(city) "mysuru" orElse "MYSURU" MISSING ofNullable(customer) has value map(address) null -> empty map(city) skipped orElse "UNKNOWN"
Figure 1: Once a step returns null, the Optional becomes empty and later steps are skipped.

5. Important Points and Best Practices

  • Use Optional mainly as a return type for methods that may not find a result.
  • Do not use it for fields, method parameters or collections; return an empty collection instead of Optional<List>.
  • Never return null from a method declared to return Optional.
  • Prefer orElseGet over orElse when the default is expensive to build.
  • Avoid calling get() without checking; Java 10 added orElseThrow() without arguments as a clearer alternative.

6. Summary

  • Optional represents a value that may be absent and was added in Java 8.
  • Create it with of, ofNullable or empty.
  • Read it with orElse, orElseGet, orElseThrow or ifPresent.
  • map and filter chains replace nested null checks.
  • Use it for return values, not for fields or parameters.

Related Tutorials

7. References