top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+1 vote
531 views
What is Optional in Java 8? What is the use of Optional? Advantages of Java 8 Optional?
posted Sep 22, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn 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, 2017 by Atindra Kumar Nath
...