Chapter FOURTEEN
Optional Class


Exam Objectives

Develop code that uses the Optional class.

Answers

1. The correct answer is C.
The method orElseGet() returns a value of the type of the Optional, it doesn't return an exception, no matter if it's not executed. For exceptions, we have to use orElseThrow().


2. The correct answer is C.
Option A is false. The method Optional.ifPresent() is the one that takes a Consumer<T> as an argument that is executed only if the Optional contains a value.
Option B is false. The method Optional.of() cannot create an empty Optional.
Option C is true. The method Optional.of() can throw a NullPointerException if its argument is null.
Option D is false. The method Optional.ifPresent() takes a Consumer<T> as an argument.


3. The correct answer is D.
The program is passing an invalid number to the method, so an exception is thrown by Integer.parseInt() and Optional.empty is returned. The method get() throws an exception if the Optional has an empty value, and this is exactly what happens.


4. The correct answer is A.
The orElse() method returns the argument when the Optional is empty, otherwise, it returns the encapsulated value of the Optional, in this case, 0.