nerdexam
Oracle

1Z0-809 · Question #201

Given the code fragments: public static Optional<String> getCountry(String loc) { Optional<String> couName = Optional.empty(); if ("Paris".equals(loc)) couName = Optional.of("France"); else if…

The correct answer is D. France Not Found. D is correct because orElse() on an Optional unwraps the contained value - it returns a raw String, not an Optional<String>. city1.orElse("Not Found") returns the unwrapped "France", and since city2.isPresent() is false (Las Vegas has no matching city), execution falls to the…

Question

Given the code fragments: public static Optional<String> getCountry(String loc) { Optional<String> couName = Optional.empty(); if ("Paris".equals(loc)) couName = Optional.of("France"); else if ("Mumbai".equals(loc)) couName = Optional.of("India"); return couName; } and Optional<String> city1 = getCountry("Paris"); Optional<String> city2 = getCountry("Las Vegas"); System.out.println(city1.orElse("Not Found")); if (city2.isPresent()) System.out.println(x -> System.out.println(x)); else System.out.println(city2.orElse("Not Found")); What is the result?

Options

  • AFrance Optional[NotFound]
  • BOptional[France] Optional[NotFound]
  • COptional[France] Not Found
  • DFrance Not Found

How the community answered

(28 responses)
  • A
    7% (2)
  • B
    14% (4)
  • C
    4% (1)
  • D
    75% (21)

Explanation

D is correct because orElse() on an Optional unwraps the contained value - it returns a raw String, not an Optional<String>. city1.orElse("Not Found") returns the unwrapped "France", and since city2.isPresent() is false (Las Vegas has no matching city), execution falls to the else branch where city2.orElse("Not Found") returns the fallback string "Not Found".

A is wrong because "Optional[NotFound]" implies orElse wraps its return in an Optional - it does not.
B and C are wrong for the same core reason: orElse() never returns "Optional[France]"; calling it on a populated Optional yields the unwrapped value directly.
The red-herring lambda x -> System.out.println(x) in the if branch is never reached, so it has no effect on output.

Memory tip: Think of orElse as "give me the value OR else give me this default" - it always hands back a plain value, never an Optional wrapper. If you see Optional[...] in an answer choice for orElse() output, eliminate it immediately.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice