Java 25 (LTS) reference · 5 entries

Java Optional

Java Optional: ofNullable(), orElse(), orElseGet(), map(), ifPresent() and orElseThrow(), for handling values that might be missing without null checks.

Optional is designed for return values that may be absent. Avoid it for fields and parameters, and never call get() without checking: use orElse, orElseThrow or ifPresent.

NameDescriptionSince
Optional.ofNullable() Wrap a value that might be null in an Optional, making 'no value' explicit. Optional.of() rejects null. Java 8
optional.orElse() Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed. Java 8
optional.map() Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks. Java 8
optional.ifPresent() Run an action with the value only if it's present. ifPresentOrElse() also handles the empty case. Java 8
optional.orElseThrow() Return the value if present, otherwise throw: NoSuchElementException by default, or an exception you supply. Java 10

Was this page helpful?