What is ObjectUtils.firstNonNull in Java?

firstNonNull() is a staticthe methods in Java that can be called without creating an object of the class. method of the ObjectUtils class that is used to return the first non-null value from a list of objects.

How to import ObjectUtils

The definition of ObjectUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the [Maven Repository](https://mvnrepository.com/artifact/org.apache.commons/commons-la ng3).


You can import the ObjectUtils class as follows:


import org.apache.commons.lang3.ObjectUtils;

Syntax

public static <T> T firstNonNull( T... values)

Parameters

values: The list of objects to test.

Return value

This method returns the first value that isn’t null. Otherwise, the method returns null if all the values are null or if the array is null or empty.

Code

import org.apache.commons.lang3.ObjectUtils;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] strings = {null, "hi", null, null, "hello"};
System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));
System.out.println();
strings = new String[]{null, null, null};
System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));
System.out.println();
strings = null;
System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));
System.out.println();
strings = new String[0];
System.out.printf("The output of ObjectUtils.firstNonNull() for the string - '%s' is '%s'", Arrays.toString(strings), ObjectUtils.firstNonNull(strings));
System.out.println();
}
}

Output

The output of the code will be as follows:


The output of ObjectUtils.firstNonNull() for the string - '[null, hi, null, null, hello]' is 'hi'
The output of ObjectUtils.firstNonNull() for the string - '[null, null, null]' is 'null'
The output of ObjectUtils.firstNonNull() for the string - 'null' is 'null'
The output of ObjectUtils.firstNonNull() for the string - '[]' is 'null'

Explanation

Example 1

  • objects = [null, "hi", null, null, "hello"]

The method returns hi, the first non-null value in the array.

Example 2

  • objects = null

The method returns false because the array/list of objects points to null.

Example 3

  • objects = [null, null, null]

The method returns null because all the values in the array/list of objects point to null.

Example 4

  • objects = []

The method returns null because the array/list of objects is empty.