Member-only story
Is Optional class methods compulsory in Java?
In this tutorial, we’re going to show the Optional class that was introduced in Java 8.
Introduction To Optional :
Optional<T> is a wrapper class with a very simple functionality.
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Optional<Employee> employeeOptional = OptionalTest.getEmployeeOpt();
if(employeeOptional.isPresent()) {
System.out.println("Employee : " + employeeOpt.get());
}
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
Optional<Employee> employeeOptional = Optional.ofNullable(OptionalTest.getEmployeeOpt().orElse(defaultEmployee()));
There are three ways to create an instance of Optional:
// an empty ‘Optional’;
Optional<String> empty = Optional.empty();
// an ‘Optional’ where you know that it will not contain null;
Optional<String> mustNonNull = Optional.of(“Some String”);