Junior — Middle
Can you explain what the Optional class in Java is and what it is used for?
sobes.tech AI
Answer from AI
The Optional class in Java is a container that may either contain a value or be empty (null). Its main purpose is to help avoid errors related to NullPointerException and to make code more readable and safe when working with potentially absent values.
Example of usage:
Optional<String> optionalName = Optional.ofNullable(getName());
if (optionalName.isPresent()) {
System.out.println("Name: " + optionalName.get());
} else {
System.out.println("Name not provided");
}
Additionally, Optional provides convenient methods such as orElse(), orElseGet(), map(), which allow working with the value without explicit null checks.