Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is StringUtils.defaultString in java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 str is the string that is passed.
  • final String defaultStr is 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

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring