Junior — Middle
What is the main purpose of using the Optional type in programming?
sobes.tech AI
Answer from AI
The Optional type in Java is used to explicitly represent a value that may or may not be present. The main goal is to avoid errors related to null (such as NullPointerException) and to make the code more readable and safe. Instead of returning null, a method returns an Optional, which either contains a value or is empty.
Example:
Optional<String> getName() {
return Optional.ofNullable(name);
}
Optional<String> nameOpt = getName();
nameOpt.ifPresent(name -> System.out.println(name));