Java Tutorial · Advanced Java · Lesson 33 of 37

Java Optional

Represent 'maybe a value' explicitly and avoid NullPointerException.

Optional

Optional<T> is a container that holds a value or is empty. Returning Optional from a method makes "might not exist" part of its type, so callers can't forget to handle it:

Example 1
import java.util.Map;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        System.out.println(findEmail(1).orElse("no email"));
        System.out.println(findEmail(2).orElse("no email"));
        System.out.println(findEmail(1).map(String::toUpperCase).orElse("-"));
        findEmail(1).ifPresent(e -> System.out.println("Sending to " + e));
        System.out.println(findEmail(2).isEmpty());
        try {
            findEmail(3).orElseThrow(() -> new IllegalArgumentException("user 3 has no email"));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    static final Map<Integer, String> EMAILS = Map.of(1, "[email protected]");

    static Optional<String> findEmail(int userId) {
        return Optional.ofNullable(EMAILS.get(userId));
    }
}

Output

[email protected]
no email
[email protected]
Sending to [email protected]
true
user 3 has no email

Run this on your computer — see “Get Started” for setup.

Good practice

  • Use Optional as a return type, not for fields or parameters.
  • Prefer orElse, orElseGet, orElseThrow, map and ifPresent over isPresent() + get().
  • Never return null from a method declared to return Optional.

Test yourself

Which method returns a default when the Optional is empty?

  1. get()
  2. orElse()
  3. isPresent()
  4. of()
Show answer

Answer: orElse()