CKTIS / Java
Optional.ofNullable: practical reference
Optional.ofNullable: practical reference: Optional.ofNullable(value) returns Optional.empty() for null and retains a non-null value in the same way as Optional.of.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Optional.ofNullable(...)Optional.ofNullable(value) returns Optional.empty() for null and retains a non-null value in the same way as Optional.of.
Use it at a boundary with an API that signals absence using null, so subsequent processing can use Optional operations.
Do not use it to hide an unexpected null that violates a contract; of or requireNonNull exposes that defect earlier.
The call itself does not throw NullPointerException for null; its result is always an Optional object, never null, and the input object is not copied.
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.ofNullable(null);
System.out.println(value.isEmpty());
}
}
Result
true
The example exercises the documented element in a small deterministic program and compares exact standard output.