Optional class was introduced in Java 8. The purpose of using the class is to provide a type-level solution for representing Optional values instead of null references.
There are several ways of creating Optional objects.
- To create an empty Optional object, empty() static method must be used – Optional<T> empty = Optional.empty();
- Creating Optional object with the static method of()
String name = "somestring";
Optional<String> opt = Optional.of(name);
However, the argument passed to the of() method can’t be null. Otherwise, we’ll get a NullPointerException.
But, in case we expect some null values, we can use the
- ofNullable() method
String name = null;
Optional<String> opt = Optional.ofNullable(name);
By doing this, if we pass in a null reference, it doesn’t throw an exception but rather returns an empty Optional object.