Explaining Optionals
An Optional can be thought of as a container that may or may not be empty. As per the API, the container “may or may not contain a non-null value”. An Optional is primarily used as a method return type where there is a real need to represent “no result” and when returning null could cause errors. Before Java 8, programmers would return null but now, since Java 8, we can return an empty Optional instead. This has several advantages:
- Reduces the risk of
NullPointerExceptions - By using
Optionalas the return type, the API can now clearly state that there may not be a value returned - The
OptionalAPI facilitates the functional programming style
As well as Optional<T>, there are Optionals for the primitive types also; namely: OptionalInt, OptionalDouble and OptionalLong. We will examine them later.
Let us first look at how to create Optionals.
Creating Optionals
The API provides several static methods for...