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.
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.
StringUtils
in JavaStringUtils
class can be imported as follows:
import org.apache.commons.lang3.StringUtils;
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr)
final T str
: string to check.
final T defaultStr
: the default string.
The return value is the passed string or the default string.
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"));}}
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.