The Optional class in Java (introduced in Java 8) is a container object used to represent the presence or absence of a value. It helps avoid NullPointerException and encourages safer, cleaner code.
null checksjava.util packageAn Optional object can either contain a non-null value or be empty. Instead of returning null, methods can return Optional to indicate optional results.
// Creating Optional objects using different factory methods
Optional name = Optional.of("Java");
Optional emptyValue = Optional.empty();
Optional nullableValue = Optional.ofNullable(null);
// Accessing values safely using Optional methods
Optional language = Optional.of("Java");
if (language.isPresent()) {
System.out.println(language.get());
}
The isPresent() method checks whether a value exists inside the Optional. The get() method retrieves the value safely when present.
See how Optional safely handles nulls without crashing. Click a button below!
// Click a button above to run code...
Optional as return types, not fieldsget() without checking presenceorElse() or orElseGet()Optional for serializationCreate a method that returns an Optional<Integer>. Test it with valid and null values and handle both cases using orElse().