Java SE 8 Programmer II Exam Question Answer: Result Explanation

Java SE 8 Programmer II Exam Question Answer: Result Explanation

Question

Given the code fragments: class Employee{ Optional<Address> address; Employee (Optional<Address> address){ this.address = address; } publicOptional<Address> getAddress(){return address;} } class Address{ String city = "New York"; public String getCity{return city:} public String toString() { return city; } } and Address address = null; Optional<Address> addrs1 = Optional.ofNullable (address); Employee e1 = new Employee (addrs1); String eAddress = (addrs1.isPresent()) ? addrs1.get().getCity() : "City Not available"; What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The given code defines two classes Employee and Address. The Employee class has an Optional<Address> field named address and a constructor that takes an Optional<Address> parameter and sets it to the address field. The Employee class also has a getter method named getAddress() that returns the Optional<Address> instance stored in the address field.

The Address class has a String field named city and two methods: getCity() that returns the value of the city field and toString() that returns the city field.

The code then creates a null Address object and uses the Optional.ofNullable() method to create an Optional<Address> instance named addrs1 with the null Address object as its value. This is then passed to the Employee constructor to create an Employee object named e1.

Finally, a String variable named eAddress is initialized with a ternary operator. The addrs1.isPresent() method is used to check if the Optional<Address> instance stored in addrs1 has a value or not. Since addrs1 was created with a null Address object, it does not have a value, so addrs1.isPresent() returns false. The ternary operator then sets the value of eAddress to "City Not available" since there is no Address object to get the city from.

Therefore, the result is option B: "City Not available".