Given the code fragments:
andWhat is the result?
Given the code fragments:
andWhat is the result?
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'.
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; } }
D is the answer
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; } }
D is correct.