Java Optional Class
In this page:
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;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Meera");
Optional<String> empty = Optional.empty();
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;
public class Main {
public static void main(String[] args) {
Optional<String> value = Optional.of("data");
if (value.isPresent()) {
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;
public class Main {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
System.out.println(empty.orElse("default value"));
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;
public class Main {
public static void main(String[] args) {
Optional<String> value = Optional.of("present");
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;
public class Main {
public static void main(String[] args) {
Optional<Integer> result = Optional.of(10)
.filter(n -> n > 5)
.map(n -> n * 2);
System.out.println(result.get());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: