Java OCA OCP Practice Question 1711

Question

Fill in the blanks so that both methods produce the same output for all inputs.

private static void longer(Optional<Boolean> opt) {
   if (opt.___())
      System.out.println("run: " + opt.get());
}
private static void shorter(Optional<Boolean> opt) {
   opt.map(x -> "run: " + x).___(System.out::println);
}
A.  isNotNull, isPresent
B.  ifPresent, isPresent
C.  isPresent, forEach
D.  isPresent, ifPresent


D.

Note

The Optional class has an isPresent() method that doesn't take any parameters.

It returns a boolean and is commonly used in if statements.

There is also an ifPresent() method that takes a Consumer parameter and runs it only if the Optional is non-empty.

The methods isNotNull() and forEach()are not declared in Optional.

Therefore, Option D is correct.




PreviousNext

Related