Core Java

Optional ofNullable() method (With Examples)

A quick guide to Optional ofNullable() method in Java 8 API with Example programs. How to use in the real time projects.

1. Introduction

In this tutorial, We’ll learn Optional ofNullable() example on how to create new Java 8 Optional object for any value or null value. Optional is part of  java.util package.

API Note: Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.

This method same as  Optional.of() method and additionally supports null values. It does not throw NullPointerException if we pass null to it.

If we are not sure about the value then using  ofNullable() method is suggestable.

Let us see the syntax and example programs.

2. Optional ofNullable Syntax

ofNullable syntax is below.

1
public static <T> Optional<T> ofNullable(T value)

ofNullable() is a static method and can be accessed directly with the class name.  ofNullable() returns Optional object.

This method accepts any type of value.

3. Java 8 ofNullable() Example

Let us write an example java program on ofNullable().

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.java.w3schools.blog.java8.optional;
 
import java.util.Optional;
 
/**
 * Java 8 Optional ofNullable() Method Example
 *
 * @author Venkatesh
 *
 */
public class OptionalOfNullableExample {
 
 public static void main(String[] args) {
 
  // A non-null value is passed
  Optional<String> indiaOptional = Optional.ofNullable(getValue("India"));
  System.out.println("indiaOptional : " + indiaOptional);
 
  // A null value is passed
  Optional<String> usOptional = Optional.ofNullable(getValue("United States"));
  System.out.println("usOptional : " + usOptional);
 
  System.out.println(indiaOptional.isPresent());
  System.out.println(usOptional.isPresent());
 }
 
 private static String getValue(String key) {
 
  if ("India".equals(key)) {
   return "Delhi";
  } else if ("Australia".equals(key)) {
   return "Sidney";
  }
 
  return null;
 }
 
}

Output:

1
2
indiaOptional : Optional[Delhi]
usOptional : Optional.empty

Assume that getValue() is a third party API method and we do not know the value returns. The returned value may be null or non-null. In such cases, We should use ofNullable() instead of of() method.

In the output, We are seeing the value for the indiaOptional as Delhi. But, seeing Optional.empty for usOptional. Because ofNullable method internally calls  Optional.empty() method if the null value is passed to it.

Internal Implementation Code:

See the internal logic to understand how it is implemented. This method uses two methods. If the value is null, it calls  empty() method. If the value is non-null, it calls  of() method.

1
2
3
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

Let us take a look at the below example to check value is present using 
isPresent() method.

1
2
System.out.println(indiaOptional.isPresent());
System.out.println(usOptional.isPresent());

Output:

1
2
true
false

If you use of() method, it will throw  NullPointerException.

4. Conclusion

In this article, We’ve seen  how to create an Optional object for any nullable or non-null value. This method also is a static method as empty() and of() methods of Optional class. This will not throw any runtime exception for any value.

An example scenario where to use ofNullable() method.

And also seen  its internal implementation logic.

Full example code on GitHub

API ref

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Optional ofNullable() method (With Examples)

Opinions expressed by Java Code Geeks contributors are their own.

Venkatesh Nukala

Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
anodino
anodino
1 year ago

Hi, Venkatesh Nukala, Thanks for write this tips

Back to top button