Modern Java 8+ Features ยท Safer APIs

Optional: No More null Surprises

Return Optional instead of null when a value might be missing, and handle both cases without a NullPointerException.

OptionalDemo.java

import java.util.Map;
import java.util.Optional;

public class OptionalDemo {
    static Map<String, String> emails = Map.of("asha", "asha@mail.com");

    static Optional<String> findEmail(String user) {
        return Optional.ofNullable(emails.get(user));
    }

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

        boolean hasBen = missing.isPresent();
        String benEmail = missing.orElse("no email");
        String domain = found.map(e -> e.substring(e.indexOf('@') + 1)).orElse("?");
        System.out.println(hasBen + " " + benEmail + " " + domain);
    }
}

Step by step

  1. Java calls findEmail(), with user = "asha". It gets its own variables on the stack. The program starts in main. args holds its command-line arguments (none here). The static variable OptionalDemo.emails holds {asha=asha@mail.com}. There is one copy, shared by the whole class.
  2. ofNullable wraps the result: a value if found, an empty Optional if null.
  3. The value it returned, Optional[asha@mail.com], is stored in found.
  4. Java calls findEmail(), with user = "ben". It gets its own variables on the stack.
  5. No "ben" key: the map gives null, so this Optional is empty.
  6. The value it returned, Optional.empty, is stored in missing.
  7. isPresent: false for Ben.
  8. orElse gives a fallback when the Optional is empty.
  9. map transforms the value inside, if there is one: the part after @.
  10. lambda$main$0() has finished, so its variables are gone.
  11. The value it returned, "mail.com", is stored in domain.
  12. It prints false no email mail.com.
  13. false, "no email" and "mail.com". No null checks and no NullPointerException.