Skip to Content

Optional class is available in Java8. Let’s use some examples to understand its logic.

Example 1

Optional instance acts as a wrapper for your productive Java class. For example I have a Person class:

class Person {
  private String mName;
  public Person(String name) {
   mName = name;
  public void greet() {
   System.out.println("I am: " + mName);

line 21 will trigger an null pointer exception.


Console will print out “Error: java.lang.NullPointerException – null”. To avoid it we can use method ofNullable and evaluate the availability using method isPresent. The following two lines 28 and 32 will print false and true accordingly.


Example 2

Instead of writing code like:

if ( person != null ) {

to avoid null pointer exception before Java 8, now we can write:


The lambda expression specified within method ifPresent will only be executed if the method isPresent() returns true.

Example 3

Now we can avoid the ( condition ) ? x: y statement using orElse method of Optional:



Example 4

We need to figure out if a person is Jerry or not. The old style has to always check whether the reference jerry is available or not.


The new approach is to use filter method of instance of class Optional<Person>, thus the null check could be avoided (replaced by ifPresent ).

old style-> Jerry found: Jerry
new style-> Jerry found: Jerry

The enhanced version using map function:


Difference between method map and flatMap

map accepts a function returning the unwrapped data without Optional ( type U ), and the flatMap accepts a function returning the wrapped data with Optional ( type Optional<U> ).


To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply