top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

What is Optional in Java 8? What is the use of Optional? Advantages of Java 8 Optional?

+1 vote
posted Sep 22 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+1 vote

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent.

There are 3 ways to create an instance of Optional:

<!-- before Java 8 you would simply use a null reference here -->
 Optional<String> empty = Optional.empty();
<!-- (if the parameter for 'of' is null, a 'NullPointerException' is thrown) -->
 Optional<String> full = Optional.of("Some String");
 <!-- an 'Optional' where you don't know whether it will contain null or not -->
 Optional<String> halfFull = Optional.ofNullable(someOtherString);

The most basic methods of Optional are:

boolean isPresent() -- returns true if the value is present, i.e. if it was not constructed as empty or of a null reference
T get() -- returns the value if it is present; otherwise a NoSuchElementException is thrown

Advantages of Java 8 Optional:

  • No more NullPointerException at run-time.
  • Null checks are not required.
  • No more Boiler plate code
  • We can develop clean and neat APIs.
answer Sep 22 by Atindra Kumar Nath

Useful Links with Similar Problem
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.