Java MCQ: What is the purpose of the Optional class in Java 8?
Answer:
Explanation:
The Optional
class in Java 8 is used to provide a container object that may or may not contain a non-null value. It is a utility class introduced to help avoid NullPointerException
and to represent the concept of an optional value, which may or may not be present.
Here’s an example of using Optional
:
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optionalName = Optional.ofNullable(null);
String name = optionalName.orElse("Default Name");
System.out.println(name);
}
}
In this example, an Optional
is created using Optional.ofNullable()
with a null value. The orElse()
method is then used to provide a default value if the Optional
is empty (i.e., it contains null). The result is “Default Name” printed to the console.
Optional
provides a way to handle null values more gracefully, making code more readable and less prone to errors. It offers methods such as isPresent()
, ifPresent()
, orElse()
, and orElseGet()
to work with optional values in a functional style.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html