To learn about Optional, visit http://talks.skilltoz.com/optional-in-java/
For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/
Practice Questions (Answers below)
Q1. Which of these code fragments will cause a NullPointerException?
a. Optional<String> opt1 = Optional.empty();
boolean b1 = opt1.isPresent();
b. Optional<String> opt2 = Optional.ofNullable(null);
boolean b2 = opt2.isPresent();
c. Optional<String> opt3 = Optional.of(null);
boolean b3 = opt3.isPresent();
d. None of the above
Q2. What is the result?
class Employee {
private String name;
private Integer id;
public Employee(int id, String name) {
this.name = name;
this.id = id;
}
// Getters and Setters
}
public class Optional4 {
public static void main(String args[]) {
Employee employee1 = findEmployee((int).1*10);
System.out.println(employee1.getName());
}
public static Employee findEmployee(Integer id) {
Employee employee = null;
if (id.equals(1)) {
employee = new Employee("Tom", 21);
}
Optional<Employee> opEmployee = Optional.ofNullable(employee);
employee = opEmployee.orElse(new Employee(0, "Unknown Employee"));
return employee;
}
}
Choices
a. Prints “Tom”
b. Prints “Unknown Employee”
c. Compiler error
d. NullPointerException at runtime
Answers
Q1. Choice c is the correct answer. If a null argument is passed to the of() method of Optional class, it causes NullPointerException to be thrown.
Q2. Choice b is the correct answer. The expression (int).1 evaluates to 0 which multiplied by 10 would again return 0 itself. Hence, the value 0 is passed to the findEmployee() method.
The ofNullable() method returns the Optional Instance as empty as employee is null. The orElse() method returns the wrapped value if it’s present and its argument otherwise. In this case as no value is present, the argument “Unknown Employee” itself is returned.