Java SE 8 Programmer II — Question 107

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 = new Address;
Optional<Address> addrs1 = Optional.ofNullable (address);
Employee e1 = new Employee (addrs1);
String eAddress = (addrs1.isPresent()) ? addrs1.get().getCity() : "City Not available";
System.out.println(eAddress);
What is the result?

Answer options

Correct answer: C

Explanation

The correct answer is C because the address variable is not initialized properly; it lacks the parentheses to create a new instance of Address. As a result, addrs1 is created with a null value, and when checked, it does not find a present value. Therefore, the expression evaluates to null. Options A and B are incorrect because they imply a valid address object exists, and D is incorrect as no exception is thrown due to the use of Optional.