Java 8 Optional In Depth
Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException
. It avoids any runtime NullPointerExceptions
and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value. Let us explore this new construct with some useful examples.
Advantages of Java 8 Optional:
- Null checks are not required.
- No more NullPointerException at run-time.
- We can develop clean and neat APIs.
1. Optional Basic example
Optional.ofNullable()
method returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional.
Optionaal.empty()
method is useful to create an empty Optional object.