Java MCQ: What does the Optional.empty() method return?
a) An empty List
b) An Optional containing a null value
c) An Optional with no value present
d) An Optional containing an empty string
Answer:
c) An Optional with no value present
Explanation:
The Optional.empty()
method returns an Optional
with no value present. This method is used to create an Optional
object that represents the absence of a value.
Here’s an example of using Optional.empty()
:
import java.util.Optional;
public class OptionalEmptyExample {
public static void main(String[] args) {
Optional<String> optional = Optional.empty();
System.out.println("Is value present: " + optional.isPresent());
}
}
In this example, Optional.empty()
creates an empty Optional
object. The isPresent()
method is then used to check whether the Optional
contains a value, which in this case it does not, so false
is printed.
Optional.empty()
is useful when you want to explicitly represent the absence of a value in a type-safe way, avoiding the use of null and reducing the risk of NullPointerException
.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html