JAVA8 Optional Best Practices

Gain Java Knowledge
3 min readFeb 23, 2021

Optional was introduced in jdk8. It is a public final class and used to avoid NullPointerException in Java application.

It is a public final class which is used to avoid NullPointerException in java application. It was introduced in Java8. As we know java is an object oriented programming language . So sometime object contain some value or sometime null. To avoid NullPointerException we can use Optional class.

Okay, Lets create one java class to check usage of Optional class in java application.

First I will create one model class i.e. User.java. It containing 3 fields id, name and city.

There are 3 different ways to create Optional Object.

  1. empty()
  2. of(parameter)
  3. ofNullable(parameter)

Optional<Object> empty = Optional.empty();
System.out.println(empty);

Here, We are using empty() method i.e. static method provided by Optional class to create Empty Optional object.

OptionalTest.java

User user = new User(1, “reddy”, “hyderabad”);
Optional<String> city = Optional.of(user.getCity());

--

--

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.