Q1. Name few "Optional" classes introduced with Java 8 ?
Q2. What will the following code result ?
List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();
intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));
System.out.println(intList.get(null));
Ans. Compile time error at last line as the get method expect argument of type native int.
Q3. What will the following code result ? Will it compile ?
List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();
intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));
System.out.println(intList.get((Integer)null));
Ans. Yes but the last line will throw NullPointerException upon execution.
Q4. 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.