JAVA8 Optional Best Practices
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.
- empty()
- of(parameter)
- 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.
User user = new User(1, “reddy”, “hyderabad”);
Optional<String> city = Optional.of(user.getCity());