nerdexam
Oracle

1Z0-819 · Question #46

Given: public class Main { public static void main(String[] args) { String str = Value.orElse("Duke"); System.out.println(str); } static Optional<String> createValue() { String s = null; return…

The correct answer is C. Duke. Option C is correct because createValue() returns Optional.ofNullable(null), which produces an empty Optional rather than throwing an exception. Calling orElse("Duke") on an empty Optional returns the provided default value, so "Duke" is printed. Option A is wrong because…

Working with Streams and Lambda Expressions

Question

Given: public class Main { public static void main(String[] args) { String str = Value.orElse("Duke"); System.out.println(str); } static Optional<String> createValue() { String s = null; return Optional.ofNullable(s); } } What is the output?

Options

  • Anull
  • BA NoSuchElementException is thrown at run time.
  • CDuke
  • DA NullPointerException is thrown at run time.

How the community answered

(24 responses)
  • A
    17% (4)
  • B
    4% (1)
  • C
    75% (18)
  • D
    4% (1)

Explanation

Option C is correct because createValue() returns Optional.ofNullable(null), which produces an empty Optional rather than throwing an exception. Calling orElse("Duke") on an empty Optional returns the provided default value, so "Duke" is printed.

Option A is wrong because orElse() exists precisely to avoid returning null - when the Optional is empty, it returns the fallback argument, never null. Option B is wrong because NoSuchElementException is thrown by Optional.get() when the Optional is empty, not by orElse(). Option D is wrong because Optional.ofNullable(null) safely handles null by creating an empty Optional - a NullPointerException would only occur if you used Optional.of(null) instead.

Memory tip: Pair the methods with their risk level - get() is dangerous (throws if empty), orElse() is safe (always returns something). If you see orElse() with a non-null argument, the result will never be null or throw.

Topics

#Optional#ofNullable()#orElse()#null handling

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice