Java Optional Class
In this page:
Optional<Type> optional = Optional.ofNullable(value);
optional.isPresent();
optional.orElse(defaultValue);
optional.ifPresent(value -> action);
What is Optional?
The Optional class is a container object explicitly designed to represent the presence or absence of a value, rather than using a bare null reference. It helps you handle missing values safely and makes the possibility of 'no value' visible in a method's return type instead of being an implicit, undocumented risk.
Example: What is Optional?
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> name = Optional.of("Meera");
// Optional wraps a value that may be absent
Optional<String> empty = Optional.empty();
// Print a line to the console
System.out.println(name.isPresent() + " " + empty.isPresent());
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Presence and Retrieving Values
You can check whether a value is present inside an Optional using isPresent(), and to run some code only when a value actually exists, use the ifPresent() method instead, which avoids an explicit if-check entirely.
Example: Checking Presence and Retrieving Values
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> value = Optional.of("data");
// Check whether value.isPresent()
if (value.isPresent()) {
// Print a line to the console
System.out.println(value.get());
}
value.ifPresent(v -> System.out.println("Present: " + v));
}
}
Login to try C/C++/Java/PHP code in the editor
Safe Fallback Methods
You can provide a fallback default to use whenever the Optional turns out to be empty, using either orElse(), which always computes the default eagerly, or orElseGet(), which only computes it lazily via a supplier if it's actually needed.
Example: Safe Fallback Methods
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> empty = Optional.empty();
// Print a line to the console
System.out.println(empty.orElse("default value"));
// Print a line to the console
System.out.println(empty.orElseGet(() -> "computed lazily"));
}
}
Login to try C/C++/Java/PHP code in the editor
Throwing Exceptions with Optional
If you want a missing value to be treated as an outright error, use the orElseThrow() method to throw a chosen exception instead of silently falling back. This gives you a clean, explicit way to validate that an optional input was actually supplied before continuing.
Example: Throwing Exceptions with Optional
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> value = Optional.of("present");
// Print a line to the console
System.out.println(value.orElseThrow(() -> new IllegalStateException("missing value")));
}
}
Login to try C/C++/Java/PHP code in the editor
Transforming Optionals
You can transform the value inside an Optional using filter() and map(), letting you chain conditions and conversions together in a pipeline that automatically short-circuits to empty if any step fails — very similar in spirit to how a Stream pipeline behaves.
Example: Transforming Optionals
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<Integer> result = Optional.of(10)
.filter(n -> n > 5)
.map(n -> n * 2);
// Print a line to the console
System.out.println(result.get());
}
}
Login to try C/C++/Java/PHP code in the editor
- Calling
opt.get()without checking, which throwsNoSuchElementExceptionwhen the Optional is empty; useorElse,ifPresentorisPresentfirst. - Using
Optional.of(value)with a value that might be null, which throws aNullPointerException; useOptional.ofNullable. - Writing
orElse(expensiveCall()), which always runs the call even when a value exists; useorElseGet(() -> expensiveCall())to run it only when needed.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: