Java OCA OCP Practice Question 3099

Question

Given the class definition:

class NullableBook {
    Optional<String> bookName;
    public NullableBook(Optional<String> name) {
        bookName = name;
    }
    public Optional<String> getName() {
        return bookName;
    }
}

Choose the correct option based on this code segment:

NullableBook nullBook = new NullableBook(Optional.ofNullable(null));
Optional<String> name = nullBook.getName();
 name.ifPresent(System.out::println).orElse("Empty"); // NULL
  • a) this code segment will crash by throwing NullPointerException
  • b) this code segment will print: Empty
  • c) this code segment will print: null
  • d) this code segment will result in a compiler error in line marked with NULL


d)

Note

the ifPresent() method for Optional takes a Consumer as the argument and returns void.

hence, it is not possible to chain the orElse() method after calling the ifPresent() method.




PreviousNext

Related