Member-only story

Is Optional class methods compulsory in Java?

Gain Java Knowledge
6 min readApr 6, 2024

--

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”);

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet