Which method in the Optional class is used to provide a default value if the Optional is empty?

Java MCQ: Which method in the Optional class is used to provide a default value if the Optional is empty?

a) orElse()
b) get()
c) ifPresent()
d) orElseThrow()

Answer:

a) orElse()

Explanation:

The orElse() method in the Optional class is used to provide a default value if the Optional is empty. This method returns the value held by the Optional if it is present; otherwise, it returns the default value provided as an argument to orElse().

Here’s an example of using orElse():

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, optionalName is an Optional that is empty (contains null). The orElse() method provides a default value, “Default Name”, which is returned and printed.

The orElse() method is particularly useful for avoiding NullPointerException by providing a safe fallback value in case the Optional is empty.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top