Java 8: Optional to avoid NullPointerException

Optional models a value that may be absent, so you handle "missing" explicitly.

Code
Map<String, Integer> ages = Map.of("ava", 30);
int age = Optional.ofNullable(ages.get("ben")).orElse(-1);
System.out.println("ben age = " + age);

Optional.ofNullable(ages.get("ava"))
        .ifPresent(a -> System.out.println("ava age = " + a));
Output
ben age = -1
ava age = 30
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26