Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.empty: practical reference

Optional.empty: practical reference: Optional.empty() returns an empty Optional<T> representing absence, with its type parameter inferred from the invocation context.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Optional.empty(...)

Optional.empty() returns an empty Optional representing absence, with its type parameter inferred from the invocation context.

Use it as the explicit result of a no-value path, such as an unsuccessful lookup, instead of returning null.

Do not compare empty instances with == because the API does not guarantee a singleton; use isEmpty, isPresent, or equals.

Optional.empty() resolves ambiguous type inference; the call accepts no arguments and never contains null as a value.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        java.util.Optional<String> value = java.util.Optional.empty();
        System.out.println(value.isEmpty());
    }
}

Result

true

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources