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.