OCP Question 46, Explanation

Given the code fragments:

class Customer {
    Optional<Email> contact;
    Customer (Optional<Email> contact) {
        this.contact = contact;
    }
    public Optional<Email> getContact() {
        return contact;
    }
}
class Email {
    String email = "joe.random@planet.earth";
    public String getEmail() { return email; }
    public String toString() {
        return email;
    }
}

and

Email email = null;
Optional<Email> contact = Optional.ofNullable(email);
Customer cust = new Customer(contact);
String eEmail = (contact.isPresent()) ? contact.get().getEmail() : "N/A";
System.out.println(eEmail);

What is the result?

A. joe.random@planet.earth
B. N/A
C. null
D. A NoSuchElementException is thrown at run time

 

The correct answer is B.

 

According to the javadoc on Optional, the ofNullable() method “Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.”

So this is what happens here: since Optional.ofNullable() was supplied a null object, contact is empty, and when the ternary operator looks inside it by invoking isPresent(), the method returns false.

Defining a properly constructed email object by declaring

Email email = new Email();

would give us Joe’s contact.

Speaking of option D, a NoSuchElementException can be produced by only one method in the Optional class, namely get(). As you probably remember after following video links to Problem 18, this method is considered to be pure evil and Java coders’ nemesis. Don’t touch this poison ivy with your bare hands, put on isPresent()-gloves first.

Leave Comment

Your email address will not be published.