CKTIS / Java
Optional — a value or its absence
Optional<T> represents either a result containing a value or an empty result. Learn presence checks and safe access.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Optional<T> result = Optional.ofNullable(value);
boolean present = result.isPresent();
if (result.isPresent()) {
T item = result.get();
}java.util.Optional<T> represents a non-null value or its absence, primarily as a method result. The Optional reference itself should not be null.
Optional.of(value) rejects null with NullPointerException; Optional.ofNullable(value) converts null to an empty result. Optional.empty() creates an empty result.
Optional.isPresent() returns true when a value exists. Optional.get() returns it, but throws NoSuchElementException for an empty result. The example calls get() only after checking presence. The documentation prefers orElseThrow() over get() when absence should cause an exception.
Examples
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
Optional<String> missing = Optional.empty();
System.out.println(name.isPresent());
if (name.isPresent()) {
System.out.println(name.get());
}
System.out.println(missing.isPresent());
}
}Result
true Ada false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.