Search Tutorials


Understanding Java 8 Optional using examples | JavaInUse



Java 8 Optional using simple example

In this post we will understand the Java 8 Optional using simple examples.
Java 8 introduced a new container class java.util.Optional<T>. It wraps a single value, if that value is available. If the value is not available an empty optional should be returned. Thus it represents null value with absent value. This class has various utility methods like isPresent() which helps users to avoid making use of null value checks. So instead of returning the value directly, a wrapper object is returned thus users can avoid the null pointer exception.
Consider the Item class-
package com.javainuse.model;

public class Item {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
Consider the class ItemProcessor which returns an instance of Item class-
package com.javainuse;

import com.javainuse.model.Item;

public class ItemProcessor {

	public Item getItem() {
		// Some logic here like webservice calls or db calls
		return item;

	}
}

When we call the getItem(), the item instance is returned. We first have to check for null else this may cause NullPointerException.
	 ItemProcessor ip= new ItemProcessor();
		Item item=ip.getItem();
		if(item!=null)
		System.out.println(item.getName());
		

Now lets consider the use of Optional. Instead of item instance we return optional.
package com.javainuse;

import java.util.Optional;

import com.javainuse.model.Item;

public class OptionalItemProcessor {

	public Optional<Item> getItem() {
		// Some logic here like webservice calls or db calls..
		// if item is successfully processed in our logic..then create optional
		// using Optional.of(Object)
		return Optional.of(item);
		// else if no item is returned from our logic then
		return Optional.empty();

	}
}

Here first check if the optional element is present and only then process it. No null checks are required.
	OptionalItemProcessor ip1= new OptionalItemProcessor();
		Optional<Item> item=ip1.getItem();
		if(!item.isPresent())
		{
			System.out.println("not present");
		}else
		System.out.println(item.get().getName());
	

See Also

Java - PermGen space vs MetaSpace Understand Java 8 Method References using Simple Example Java 8 Lambda Expression- Hello World Example Java 8-Internal vs. External Iteration. Understanding Java 8 Streams using examples.