Help Us Improve. Please let us know if you were asked any question in your interview.

More Questions

Java 8 - Interview Questions and Answers on Optional

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.

 Stay Updated with Java Posts directly to your mailbox.
Enter your email address:

'
Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Would like to try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests. It's updated daily and It's Awesome.


×

Would like to try our new Java Practice Test tool.

There are more than 100 questions currently and expanding quickly. It's updated daily and It's Awesome.