Optional Class

1.What is the primary purpose of the Optional class in Java?
  • A. To replace if-else statements for all conditional logic.
  • B. To handle NullPointerException gracefully by providing a container for potentially null values.
  • C. To optimize memory usage for large collections.
  • D. To provide a new type of collection for storing elements.

To handle NullPointerException gracefully by providing a container for potentially null values.

To handle NullPointerException gracefully by providing a container for potentially null values.

2.Which method is used to create an Optional containing a non-null value?
  • A. Optional.empty()
  • B. Optional.ofNullable()
  • C. Optional.of()
  • D. Optional.create()

Optional.of()

Optional.of()

3.If an Optional object contains no value, what will get() method throw?
  • A. NullPointerException
  • B. NoSuchElementException
  • C. IllegalStateException
  • D. IllegalArgumentException

NoSuchElementException

NoSuchElementException

4.Which method can be used to provide a default value if the Optional is empty?
  • A. get()
  • B. isPresent()
  • C. orElse()
  • D. ifPresent()

orElse()

orElse()

5.What is the result of Optional.of("hello").isPresent()?
  • A. true
  • B. false
  • C. null
  • D. Compilation error

true

true