×

java · level 3 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

makes a missing value impossible to miss.

When a lookup finds nothing, older code hands back null: a reference to no object at all. Nothing warns the caller. The first time they call a method on it, the program stops with a , often far from the real mistake.

An Optional is a box that is either full or empty. Optional.of(value) makes a full one, Optional.empty() an empty one, and Optional.ofNullable(x) picks for you. The return type itself now says: this might be missing.

To open it, ask isPresent(), or give a fallback with orElse("Guest"), which hands back the value when there is one and the fallback when there is not.

import java.util.Map;
import java.util.Optional;
public class Main {
    static Optional<String> nicknameFor(String name) {
        Map<String, String> nicknames = Map.of("Robert", "Bob", "Elizabeth", "Liz");
        return Optional.ofNullable(nicknames.get(name));
    }
    public static void main(String[] args) {
        Optional<String> found = nicknameFor("Robert");
        Optional<String> missing = nicknameFor("Zainab");
        System.out.println(found.isPresent() + " " + missing.isPresent());
        System.out.println(found.orElse("no nickname"));
        System.out.println(missing.orElse("no nickname"));
        System.out.println(found);
    }
}

A map's get hands back null for a missing key, so ofNullable is the safe way to wrap it.