Java 8 Optional example

March 19, 2020 | No comments

Java 8 Optional example

Optional is a container object which can contain null or not-null objects. This class has various utility methods to facilitate code to handle values and helps in protecting from throwing null pointer exception.

Creating Optional Object

Creating Optional Object
Following code will create a empty Optional object.
Optional dummyStudent = Optional.empty();
Creating Optional Object from a non null real object
Following code will create an optional object using the static method of. If the student object is null Optional.of will throw null pointer exception.
Student student = new Student(1, "Student A");
Optional optionalStudent =  Optional.of(student);
Creating Optional Object from possible null object
Following code will create an optional object using the static method ofNullable. If the student object is null Optional.ofNullable will not throw null pointer exception.
Student nullStudent = null;
Optional optionalNullStudent =  Optional.of(nullStudent);

Guarding for Nullpointer exception while accessing Objects.

Say we want to access the name field of the student object. If the student object it self is null, then the following code will throw Nullpointer Exception
//Print students' name -> throws Nullpointer exception
System.out.println(nullStudent.getCourse().getName());
But if we work with Optional object, then we can use the method isPresent() to check whether the Optional object holds any student object or not. It is like checking if (student ==null).
Student nullStudent = null;
Optional optionalNullStudent =  Optional.ofNullable(nullStudent);

if (optionalNullStudent.isPresent()) {
  System.out.println(optionalNullStudent.get().getName());
}
Using orElse, we can return a default object if the optional object does not contain non-null real object. In the following example Optional optionalNullStudent2 contains a null object. But in the following line we are calling orElse to return a new Student Object if optionalNullStudent contains a null object.
Optional optionalNullStudent2 =  Optional.ofNullable(nullStudent);
System.out.println(optionalNullStudent.orElse(new Student()).getName());
    
Summary
  • Use of Optional helps in writing clean code and use less null check.
  • Optional should not be used as a field in a class as it is not serializable.
  • It helps in writing overloaded methods where some parameters could be null by design.

No comments :

Post a Comment

Please leave your message queries or suggetions.