Java OCA OCP Practice Question 2164

Question

Which two can independently fill in the blank to output hi? (Choose two.).

import java.util.*; 
public class Main { 
  public static void main(String[] yum) { 
    m(Optional.empty()); 
  } 
  private static void m(Optional<String> opt) { 
     System.out.println(opt.___); 
  } 
} 
A.   get("hi")
B.   get(() -> "hi")
C.   orElse("hi")
D.   orElse(() -> "hi")
E.   orElseGet("hi")
F.   orElseGet(() -> "hi")


C, F.

Note

The Optional does not contain a value.

While there is a get() method on Optional, it doesn't take any parameters, making Options A and B incorrect.

Option C is the simplest way to print the desired result.

The orElse() method returns the parameter passed if the Optional is empty.

The orElseGet() method runs the Supplier passed as a parameter, making Option F correct as well.




PreviousNext

Related