What is the use of Optional ?
Javasearch.buggybread.com
Share

Search Interview Questions


 2796 questions in repository.
 There are more than 200 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Java - Interview Questions and Answers

Not frequently asked as it was introduced with Java 8.
 Q1. What is the use of Optional ?Core Java
Admin
info@buggybread.com
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> intList = new ArrayList>();
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like      Discuss      Correct / Improve     java   java8   java 8   optional


Related Questions

  Difference between final and effectively final ? Why is effectively final even required ?
  What is StringJoiner ?
 Why can't we have diamond problem with interfaces ?
 Is it ok to use optional everywhere just to get over nullpointerexception ?
  What are new features introduced with Java 8 ?
  What is the @FunctionalInterface annotation ?
  Difference between DoubleSummaryStatistics , IntSummaryStatistics and LongSummaryStatistics ?
  Name few "Optional" classes introduced with Java 8 ?
  What are the changes in Java.io in Java 8 ?




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
 

Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked:
         

X Close this

X Close this

Help Us Improve.
Please share your
interview experience.

Company Name:   


Questions Asked: