Exam 1z0-809 All QuestionsBrowse all questions from this exam
Question 104

Given the code fragments:

and

What is the result?

    Correct Answer: D

    The `getCountry` method returns an `Optional` containing the country name based on the input location. If the input is 'Paris', it returns `Optional.of('France')`, otherwise, it returns an empty `Optional`. In the given code, `city1` is assigned the result of `getCountry('Paris')`, which is `Optional.of('France')`, and `city2` is assigned the result of `getCountry('Las Vegas')`, which is an empty `Optional`. When `city1.orElse('Not Found')` is called, it prints 'France' since `city1` is present. For `city2`, the `if (city2.isPresent())` condition evaluates to false because `city2` is empty, so `city2.orElse('Not Found')` returns 'Not Found'. Therefore, the output is 'France Not Found'.

Discussion
Tarik2190Option: D

Answer is D, public class Test { public static void main (String[] args) { Optional<String> city1 = getCountry("Paris"); Optional<String> city2 = getCountry("Las Vegas"); System.out.println(city1.orElse("Not Found")); if (city2.isPresent()) city2.ifPresent(x -> System.out.println(x)); else System.out.println(city2.orElse("Not Found")); } public static Optional<String> getCountry(String loc) { Optional<String> couName = Optional.empty(); if ("Paris".equals(loc)) couName = Optional.of("France"); else if ("Mimbai".equals(loc)) couName = Optional.of("India"); return couName; } }

asdfjhfgjuaDCVOption: D

D is the answer

asdfjhfgjuaDCV

import java.util.Optional; public class Main { public static void main(String[] args) { Optional<String> city1 = getCountry("Paris"); Optional<String> city2 = getCountry("Las Vegas"); System.out.println(city1.orElse("Not Found")); if (city2.isPresent()) { city2.ifPresent(x -> System.out.println(x)); } else { System.out.println(city2.orElse("Not Found")); } } 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; } }

steefaandOption: D

D is correct.