Java OCA OCP Practice Question 1701

Question

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);
  • A. I
  • B. I and II
  • C. I and III
  • D. None of the above


D.

Note

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.




PreviousNext

Related