Optional: do not call get() without checking

get() throws NoSuchElementException on an empty Optional, which is the same failure as a NullPointerException with extra steps. Prefer orElse, orElseGet or orElseThrow.

Code
Optional<String> empty = Optional.empty();

try {
    empty.get();
} catch (NoSuchElementException e) {
    System.out.println("get() on empty threw: " + e.getMessage());
}

System.out.println("orElse      = " + empty.orElse("default"));
System.out.println("isEmpty     = " + empty.isEmpty());
System.out.println("ofNullable  = " + Optional.ofNullable(null).orElse("was null"));
Output
get() on empty threw: No value present
orElse      = default
isEmpty     = true
ofNullable  = was null
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-30