What does the Optional.orElseThrow() method introduced in Java 10 do?

Java MCQ: What does the Optional.orElseThrow() method introduced in Java 10 do?

a) Returns the contained value if present, otherwise throws NoSuchElementException
b) Returns the contained value if present, otherwise returns null
c) Returns the contained value if present, otherwise returns a default value
d) Returns the contained value if present, otherwise throws IllegalStateException

Answer:

a) Returns the contained value if present, otherwise throws NoSuchElementException

Explanation:

The Optional.orElseThrow() method, introduced in Java 10, returns the contained value if it is present; otherwise, it throws a NoSuchElementException. This method is similar to Optional.get(), but it provides a more descriptive and safe way to handle absent values, avoiding potential pitfalls of using Optional.get() directly.

Here’s an example of using Optional.orElseThrow():

import java.util.Optional;

public class OptionalOrElseThrowExample {
    public static void main(String[] args) {
        Optional<String> optionalName = Optional.of("John");

        String name = optionalName.orElseThrow();
        System.out.println(name);

        Optional<String> emptyOptional = Optional.empty();

        // This will throw NoSuchElementException because the Optional is empty
        emptyOptional.orElseThrow();
    }
}

In this example, optionalName.orElseThrow() returns “John” because the optional contains a value. However, emptyOptional.orElseThrow() will throw a NoSuchElementException because the optional is empty.

The Optional.orElseThrow() method is useful when you need to explicitly handle the absence of a value, making your code more robust and predictable by avoiding null-related issues.

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