Optional Class
java.util.Optional Class
What is the Optional class?
The
Optional<T>class is aWrapper classthat wraps objects of type 'T', like the Integer or Double classesTherefore, an Optional instance can store reference variables of all types
Using Optional objects can simplify unexpected
NullPointerExceptionThat is, exceptions caused by null values can be handled without complex conditional statements
Creating Optional Objects
Optional objects can be created using the of() method or the ofNullable() method
of() methodReturns an Optional object with a specified non-null value
If null is stored in an Optional object created through the of() method, a
NullPointerExceptionwill be thrown
ofNullable() methodIf there is a possibility that the reference variable's value could be null, it is better to create an Optional object using the ofNullable() method
The ofNullable() method:
Returns an Optional object with the specified value if the value is not null,
Returns an empty Optional object if the specified value is null
Last updated