Which of the following creates an Optional that returns true when calling opt.isPresent()
?
I. Optional<String> opt = Optional.empty(); II. Optional<String> opt = Optional.of(null); III. Optional<String> opt = Optional.ofNullable(null);
D.
I is incorrect because isPresent()
returns false for an empty Optional.
II is incorrect because of()
throws a NullPointerException if you try to pass a null reference.
III doesn't throw an exception as the ofNullable()
is designed to allow a null reference.
However, it returns false because no value is present.
Since none of the choices are correct, Option D is the answer.