Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 17
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.Optional;
- public class Test {
- public static void main(String[] args) {
- Optional<Integer> optional = Optional.of(null); //Line 8
- System.out.println(optional.orElse(-1)); //Line 9
- }
- }
What will be the result of compiling and executing Test class?
- A -1
- B Line 8 throws NullPointerException
- C Line 9 throws NullPointerException
- D null
Reveal correct answer
Correct answer: B
Explanation
Optional.of(null); throws NullPointerException if null arguments is passes.
You can use 'Optional.ofNullable(null);' to create an empty optional.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
