Java 8 - Interview Questions and Answers on Optional

Q1.  What is the use of Optional ?

Ans. Optional is a good way to protect application from runtime nullPointerException in case the the absent value has been represented as null. So basically Optional class provides the type checking during compile time and hence will never result in NPE.

For ex -

List<Optional<Employee>> intList = new ArrayList<Optional<Employee>>();
intList.add(Optional.of(new Employee("abc")));
intList.add(Optional.of(new Employee("xyz")));
intList.add(Optional.of(new Employee("123")));

So Now , even when the first list element is empty, this code will never throw an NullPointerException.

Q2.  Name few "Optional" classes introduced with Java 8 ?