Java MCQ: What does the Optional.orElseThrow() method introduced in Java 10 do?
Answer:
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