Advanced Java · Lesson 95 of 150
Optional
Optional is a container object that may or may not hold a non-null value. It's used to represent the possibility that a value might be missing, without directly using null.
01What is Optional?
Optional is a container object that may or may not hold a non-null value. It's used to represent the possibility that a value might be missing, without directly using null.
02Why is it used?
Directly working with null values often causes unexpected NullPointerException errors. Optional forces you to explicitly check whether a value is present before using it, reducing this common source of bugs.
03Real-Life Example
Think of a sealed box labeled "may or may not contain an item," which you must deliberately open and check before assuming there's something inside. Optional represents this same "might be empty" possibility clearly, instead of silently allowing a hidden, unexpected null.
04Syntax
javaOptional<DataType> optionalValue = Optional.of(value); Optional<DataType> emptyValue = Optional.empty();
05Example Program
javaimport java.util.Optional; public class OptionalDemo { public static void main(String[] args) { Optional<String> name = Optional.ofNullable(null); System.out.println(name.isPresent() ? name.get() : "No name provided"); } }
Output:
No name provided06Key Points to Remember
Optional.of()throws an error if given anullvalue directly;Optional.ofNullable()safely allowsnull.isPresent()checks if a value exists;get()retrieves it (only safe after checkingisPresent()).Optionalis mainly intended for method return types, to clearly signal that a result might be absent.