nerdexam
Oracle

1Z0-809 · Question #54

Given the code fragments: class Employee { Optional<Address> address; Employee (Optional<Address> address) { this.address = address; } public Optional<Address> getAddress() { return address; } }…

The correct answer is B. City Not available. Optional.ofNullable(null) returns an empty Optional - not one wrapping a null, but genuinely empty - so addrs1.isPresent() evaluates to false, causing the ternary to return "City Not Available" (B). A (New York) is wrong because New York would only appear if the Optional…

Question

Given the code fragments: class Employee { Optional<Address> address; Employee (Optional<Address> address) { this.address = address; } public Optional<Address> getAddress() { return address; } } class Address { String city = "New York"; public String getCity () { return city; } public String toString() { return city; } } and Address address = null; Optional<Address> addrs1 = Optional.ofNullable (address); Employee emp = new Employee (addrs1); String eAddress = (addrs1.isPresent()) ? addrs1.get().getCity() : "City Not Available"; What is the result?

Options

  • ANew York
  • BCity Not available
  • Cnull
  • DA NoSuchElementException is thrown at run time.

How the community answered

(42 responses)
  • A
    7% (3)
  • B
    71% (30)
  • C
    17% (7)
  • D
    5% (2)

Explanation

Optional.ofNullable(null) returns an empty Optional - not one wrapping a null, but genuinely empty - so addrs1.isPresent() evaluates to false, causing the ternary to return "City Not Available" (B).

A (New York) is wrong because New York would only appear if the Optional contained an Address object, but since address was null, the Optional is empty and .getCity() is never reached. C (null) is wrong because the ternary's else-branch returns a non-null string literal; Optional exists precisely to avoid propagating nulls. D (NoSuchElementException) is wrong because that exception is thrown only when calling .get() on an empty Optional directly - the isPresent() guard here prevents that path from executing.

Memory tip: Think of Optional.ofNullable(x) as a box that may or may not contain something - if x is null, the box is empty. Always pair .get() with .isPresent() (or use .orElse()), and remember that an empty Optional is not the same as an Optional containing null.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice