$show=/label

Java Optional as Return Type

SHARE:

Learn how to use Java 8 Optional as a return type to avoid runtime NullPointerException and the scenarios where Optional can not be used.

1. Overview

In this article, you'll learn how to use Optional as a return type in java 8.  Let us explore the most useful methods when working with Optional objects.

And also where Option can not fit and the scenarios where you should not use Optional in java.

Optional is added in java 8 to make clean the code and to easy way to work with the null values.

Let us jump into the Optional return type and its most important methods.

We've already covered in-depth about Optional API

Java Optional as Return Type


2. Optional As Return Type

When you are expecting Optional as return type then the returned object may have the value or null value.

In both cases, you should use the right methods of Optional such as ofNullable(), ifPresent() and get().

package com.javaprogramto.java8.streams.optionals.returntype;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class OptionalReturnExample {

	private static Map<Integer, String> idNames = new HashMap<>();

	public static void main(String[] args) {

		idNames.put(100, "jacowith");
		idNames.put(200, "Hemon");
		idNames.put(300, "Suwaari");
		idNames.put(400, "Meanon");
		idNames.put(500, "Zulia");

		Optional<String> id300Name = getNameById(300);

		if (id300Name.isPresent()) {
			String value = id300Name.get();
			System.out.println("id 300 name : " + value);
		}

		Optional<String> idUnknown = getNameById(700);

		if (idUnknown.isPresent()) {
			String value = idUnknown.get();
			System.out.println("id 700 name : " + value);
		} else {
			System.out.println("id 700 is unknown  one");
		}

	}

	public static Optional<String> getNameById(int id) {

		String name = idNames.get(id);

		Optional<String> nameOptional = Optional.ofNullable(name);

		return nameOptional;
	}

}
 

Output:

id 300 name : Suwaari
id 700 is unknown  one
This code never throws any exception and you can use the return type Optional always.There is a another method ifPresent() and ifPresentOrElse() methods that takes Consumer functional interface.
getNameById(400).ifPresent(value -> System.out.println("id  400 value is  : " + value));
		
getNameById(900).ifPresentOrElse(value -> System.out.println("id  900 value is  : " + value),
				() -> System.out.println("id 900 not found"));
 

This is good practice to use it as a return type but there are a few situations that should not be used.

3.  When To Not Use Optional

There are some situations where really Optional should not be used and will create the data loss.

3.1 Serialization

Look at the below class which wraps the Salary in Optional.

This class is implementing the Serializable interface.

import java.io.Serializable;
import java.util.Optional;

public class Employee implements Serializable {

	private int id;
	private String name;
	private Optional<Long> salary;
	
	//  setters and  getters

}

 

When you do serialize this employee object with an optional object then it will produce the NotSerializableException at runtime.

Because the Optional class does not implement the Serializable interface. So, the Serialization process does not know how to serialize it and produce an error.

It is good practice to avoid Optional in serialization.

3.2 JSON - Jackson API

Nowadays many applications provide several services and those are based on the rest api. All of this request and responses are exposed in the form of JSON using Jackson API.

How to convert JSON to an Object in java?

When you are developing the api,  you should not use the Optional as the return type for any json attributes as below.

	
private String name;

public Optional<String> getName() {
	return Optional.ofNullable(name);
}

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


Here, you are expecting the String type for the name field in the form of Optional. This is not known to the service caller on how to send in the json as Optional. It is pain to use Optional with JSON.

3.3 JPA Entity

When you. are working with Hibernate or any ORM framework, you use the Entity classes annotated with @Entity annotation.

In the entity class, you'll declare the fields that match the database column names and data types as well.

But what happens if you declare any column with Optional as below.

@Entity
public class Employee implements Serializable {
    @Id
    private long id;
 
    private Optional<String> firstName;
	
	// other fields
 
    // ... getters and setters
}
 

Now, let us add. the employee records into the database using the persist() method.

Employee emp = new Employee();
emp.setId(1l);
emp.setFirstName(Optional.of("javaprogramto.com"));
entityManager.persist(emp);
 

Further, when you run the program, it will throw the PersistenceException.

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: com.javaprogramto.Employee] Unable to build Hibernate SessionFactory
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1015)
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:941)
	at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:56)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
	at com.javaprogramto.Employee.PersistOptionalTypeExample.<clinit>(PersistOptionalTypeExample.java:11)
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Optional, at table: Employee, for columns: [org.hibernate.mapping.Column(firstName)]
 

But instead of declaring the field as Optional, you can use the getter method returns the Optional<String> value using Optional.ofNullable(this.firstName).

Even though it is not recommended to use and breaks the traditional approach.

4. Conclusion

In this article, you have seen how to use Optional as a return type in java 8.

What are the other areas not suggested to use? such as serialization, JSON, JPA, and expression language.

Examples are over GitHub.

Optional API

Ref

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,13,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,78,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Optional as Return Type
Java Optional as Return Type
Learn how to use Java 8 Optional as a return type to avoid runtime NullPointerException and the scenarios where Optional can not be used.
https://1.bp.blogspot.com/-cGG3_8CxOZU/X1kq4ULf8hI/AAAAAAAAC80/6Hc9W0eU6KUYMDpx1tWJk588W8RM7mregCLcBGAsYHQ/w640-h362/Java%2BOptional%2Bas%2BReturn%2BType.png
https://1.bp.blogspot.com/-cGG3_8CxOZU/X1kq4ULf8hI/AAAAAAAAC80/6Hc9W0eU6KUYMDpx1tWJk588W8RM7mregCLcBGAsYHQ/s72-w640-c-h362/Java%2BOptional%2Bas%2BReturn%2BType.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/09/java-optional-as-return-type.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/09/java-optional-as-return-type.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content