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.empty());
intList.add(Optional.of(new Employee("abc")));
intList.add(Optional.of(new Employee("xyz")));
intList.add(Optional.of(new Employee("123")));
System.out.println(intList.get(0).getName());

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 ?

Ans. http://www.buggybread.com/2015/01/java-optional-classes-and-interfaces.html