Junior — Middle
How do we use the Optional class from the standard library to handle potentially missing values?
sobes.tech AI
Answer from AI
The Optional class is used for safe handling of potentially absent values to avoid errors related to null (such as NullPointerException). It wraps a value that may be present or absent and provides methods for safe access and processing.
Main methods of Optional:
of(value)— creates an Optional with a non-null value.empty()— creates an empty Optional.isPresent()— checks if a value is present.orElse(defaultValue)— returns the value or a default if absent.map(function)— applies a function to the value if present.
Example in Java:
Optional<String> optionalName = Optional.ofNullable(getName());
String name = optionalName.orElse("Unknown");
optionalName.ifPresent(n -> System.out.println("Name: " + n));
This approach helps write more reliable and cleaner code, avoiding explicit null checks.