What is StringUtils.firstNonEmpty in Java?

firstNonEmpty is a static method of the StringUtils class that returns the first element in a given list of elements that is not empty. If all the elements are null or empty then null is returned.

How to import StringUtils

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added 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.

You can import the StringUtils class as follows.

import org.apache.commons.lang3.StringUtils;

Syntax


public static <T extends CharSequence> T firstNonEmpty(final T... values)

Parameters

  • final T... values: list of values to test

To understand what ... is, refer to What are the three dots in Java?

Return value

The function returns the first non-empty value

Code

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String[] strings = {null, ""};
System.out.println("First Non-Empty for the strings - " + StringUtils.firstNonEmpty(strings));
strings = new String[]{null, "", " ", "educative.io", null, " "};
System.out.println("First Non-Empty for the strings - " + StringUtils.firstNonEmpty(strings));
strings = new String[]{null, "", "educative.io", null, " "};
System.out.println("First Non-Empty for the strings - " + StringUtils.firstNonEmpty(strings));
}
}

Explanation

  • string list: [null, ""]

The output of the method when the string list above is passed is null, as there are no non-null and non-empty elements in the list.

  • string list: [null, "", " ", "educative.io", null, " "]

The output of the method when this string list is passed is " " i.e. the first string that is not empty, null or whitespace only. Here, whitespace is considered a non-empty string having a whitespace character.

  • string list: [null, "", "educative.io", null, " "]

The output of the method when this string list is passed is educative.io i.e. the first string that is not empty or null.

Expected output


First Non-Empty for the strings - null
First Non-Empty for the strings - "   "   
First Non-Empty for the strings - educative.io

Free Resources