What is StringUtils.defaultIfEmpty in Java?

Overview

defaultIfEmpty is a static method of the StringUtils class that works as follows:

  • The method takes in two parameters, i.e., a string and a default string.

  • If the passed string is null or empty then the default string is returned. Otherwise the string is returned.

Add Apache Commons Lang package

StringUtils is defined in the Apache Commons Lang package. To add the Apache Commons Lang package to the Maven project, add the following dependency to the pom.xml file.


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

Note: For other versions of the commons-lang package, refer to the Maven Repository.

How to import StringUtils in Java

StringUtils class can be imported as follows:


import org.apache.commons.lang3.StringUtils;

Syntax


public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr)

Parameters

  • final T str: string to check.

  • final T defaultStr: the default string.

Return value

The return value is the passed string or the default string.

Code

In the code below, we pass different values for string and the default string parameters to the defaultIfEmpty method.

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args)
{
System.out.println(StringUtils.defaultIfEmpty("", "defaultString"));
System.out.println(StringUtils.defaultIfEmpty(null, "defaultString"));
System.out.println(StringUtils.defaultIfEmpty("passedString", "defaultString"));
System.out.println(StringUtils.defaultIfEmpty(" ", "defaultString"));
}
}

Output

The output of the following code is as follows:

defaultString
defaultString
passedString
 

The last value in the output above is a space character (" ") as space is not an empty string.