What is StringUtils.defaultString in java?
Overview
The defaultString 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.
- The default string is returned if the passed string is
null. - Otherwise, the passed string is returned.
StringUtils is defined in the Apache Commons Lang package. The Apache Commons Lang can be added to the Maven project by adding the following dependency to 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 Maven Repository
StringUtils class can be imported as follows:
import org.apache.commons.lang3.StringUtils;
Syntax
public static String defaultString(final String str, final String defaultStr)
Parameters
final String stris the string that is passed.final String defaultStris the default string.
Returns
The default string returns if the passed string is null. Otherwise it returns the passed string.
Code
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {System.out.println(StringUtils.defaultString("AbaBAaaabBbCCcaC", "defaultValue1"));System.out.println(StringUtils.defaultString(null, "defaultValue2"));}}
Output
AbaBAaaabBbCCcaC
defaultValue2