Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.of: practical reference

Optional.of: practical reference: Optional.of(value) creates an Optional with a necessarily present non-null value and preserves its inferred generic type.

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

Syntax

Optional.of(...)

Optional.of(value) creates an Optional with a necessarily present non-null value and preserves its inferred generic type.

Use of when null violates the contract and should be detected immediately where the Optional is created.

Do not use of for nullable input because it throws instead of producing empty; choose ofNullable for that contract.

Passing null always throws NullPointerException; the method does not copy the object, so later mutation of the contained object remains visible.

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 {
        var value = java.util.Optional.of("Java");
        System.out.println(value.get());
    }
}

Result

Java

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

Sources