Java Programming Tutorials

Java programming tutorials with many code examples!

Java Util Optional.ofNullable(T)

java.util.Optional.ofNullable(T)

The method Optional.ofNullable(T) returns Optional containing given value if it was not null or an empty Optional in case of null value.

This is very practical method that can be used to provide default value, when the expected value is null.

Method signature

The signature of the java.util.Optional.ofNullable(T) method is as follows:

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

The method is available since Java 8.

Parameters

The method takes possibly null object as a parameter.

Return value

Returns on Optional containing given value if it was not null, or an empty Optional.

Exceptions

The method throws no exceptions.

Example usage

In the following code we use java.util.Optional.ofNullable(T):

package com.farenda.java.util;

import java.util.Optional;

public class OptionalExamples {

    public static void main(String[] args) {
        String name = null;
        Optional<String> value = Optional.ofNullable(name);
        System.out.println("Is present: " + value.isPresent());
        if (value.isPresent()) {
            System.out.println("Current value: " + value.get());
        }

        value = Optional.ofNullable("Monika");
        System.out.println("Is present: " + value.isPresent());
        if (value.isPresent()) {
            System.out.println("Current value: " + value.get());
        }
    }
}

The above code produces the following output:

Is present: false
Is present: true
Current value: Monika

Alternatives:

  • Simple if-else:

    String value = (value != null) ? value : defaultValue;
    
  • Guava’s Objects.firstNotNull(value, defaultValue)
Share with the World!