Java Optional — Free Java Tutorial
Learn Java Optional in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Optional in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Optional in Java
Optional<T> (java.util.Optional) is a container that may or may not hold a non-null value. It was introduced in Java 8 to make null-handling explicit and reduce NullPointerExceptions.
Create with: Optional.of(value) (throws NPE if null), Optional.ofNullable(value) (safe, accepts null), Optional.empty() (no value).
Key methods: isPresent(), isEmpty() (Java 11+), get() (throws if empty), orElse(default), orElseGet(supplier), orElseThrow(), ifPresent(consumer), map(), filter().
Optional is best used as a return type for methods that might not find a result — never use it as a field type or method parameter.
Java Optional — Syntax
Optional<String> opt = Optional.ofNullable(getValue());
opt.isPresent() // true if value exists
opt.get() // get value (throws if empty)
opt.orElse("default") // value or default
opt.orElseGet(() -> compute()) // value or lazy default
opt.orElseThrow()
Learn Java Optional step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →