Java introduced the Optional
class in Java 8 as part of the java.util
package. It provides a more eloquent way to deal with cases that may or may not produce a value, thus helping to handle the absence of value situations without null references. Since its inception, Optional
has been frequently used as a return type for methods, emphasizing that the method might not always return a meaningful value.
In this article, we’ll discuss some of the commonly asked interview questions related to Java Optionals, along with their short answers.
If you don’t have a medium membership, you can use this link to reach the article without a paywall.
1. What is Java Optional
?
Optional
is a container object that may or may not contain a non-null value. If a value is present, Optional.isPresent()
returns true
and Optional.get()
returns the value. Otherwise, isPresent()
returns false
and get()
throws a NoSuchElementException
.