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
Options
- AFrance Optional[NotFound]
- BOptional[France] Optional[NotFound]
- COptional[France] Not Found
- DFrance Not Found
How the community answered
(28 responses)- A7% (2)
- B14% (4)
- C4% (1)
- D75% (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.