What is StringUtils.appendIfMissing in java?

The appendIfMissing is the static method of the StringUtils that is used to append a given suffix at the end of a string if it does not already end with one on the given list.

This method is case-sensitive which checks whether the string ends with the given list of suffixes. For case-insensitive method with the same functionality refer to What is StringUtils.appendIfMissingIgnoreCase in java?

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>

Note: 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 String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes)

Parameters

The function takes on the following parameters as described below.:

  • final String str is the string to check and append.
  • final CharSequence suffix is the suffix to append to the string.
  • final CharSequence... suffixes is the list of suffixes that are valid terminators.

Return value

The return value is a new string with the suffix appended. Otherwise, the same string will be returned in case the string ends with any of the suffixes.

Code

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String beforeAppending = "hello-educative";
String suffix = "-edpresso";
System.out.println(StringUtils.appendIfMissing(beforeAppending, suffix, "hello", "educat"));
System.out.println(StringUtils.appendIfMissing(beforeAppending, suffix, "hello", "educat", "tive"));
}
}

Output

The output of the code will be as follows:

hello-educative-edpresso
hello-educative

Explanation

  • String = "hello-educative"
  • Suffix = "-edpresso"
  • Suffixes list = ["hello", "educat"]

The function would append the suffix to the string and return hello-educative-edpresso, because the string does not end with any of the values in the suffixes list.

  • String = "hello-educative"
  • Suffix = "-edpresso"
  • Suffixes list = ["hello", "educat", "tive"]

The function would not append the suffix to the string and returns the same input string hello-educative, because the string ends with the "tive" value in the suffixes list.

Free Resources