What is the purpose of the Guava Optional class?
A) To handle nullable values in a safe way
B) To manage optional configuration files
C) To provide an alternative to method overloading
D) To store optional data in a map
Answer:
A) To handle nullable values in a safe way
Explanation:
The Guava Optional class is used to handle nullable values in a safe way. It is a container object that may or may not contain a non-null value. Optional is designed to help avoid NullPointerException by explicitly handling the presence or absence of a value.
For example:
Optional<String> optional = Optional.ofNullable(someString);
if (optional.isPresent()) {
System.out.println(optional.get());
} else {
System.out.println("Value is absent");
}
In this example, Optional.ofNullable() creates an Optional that contains someString if it is not null, or an empty Optional if it is null. The isPresent() method checks whether a value is present, and get() retrieves the value if it is present.