Trusted answers to developer questions

What is StringUtils.endsWith in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

endsWith is a static method of the StringUtils class that checks whether the given string ends with the given string/suffix. This method is case-sensitive when comparing the suffix with the end of the string.

Some special cases to look out for are as follows:

  1. The method returns true when the input string and the suffix are null. Two null references are considered to be equal.
  2. The method returns false when the input string or the suffix is null.

Note: For case-insensitive comparison, use StringUtils.endsWithIgnoreCase.

How to import StringUtils

StringUtils is defined in the Apache Commons Lang package. Add Apache Commons Lang 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 boolean endsWith(final CharSequence str, final CharSequence suffix)

Parameters

The function takes in two parameters:

  • final CharSequence str: the character sequence to check
  • final CharSequence suffix: the suffix to find in the string

Return value

The function returns true if the string ends with the suffix. Otherwise, it returns false.

Code

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String string = "educative";
String suffix = "tive";
System.out.println(StringUtils.endsWith(string, suffix));
suffix = "edu";
System.out.println(StringUtils.endsWith(string, suffix));
System.out.println(StringUtils.endsWith(string, null));
System.out.println(StringUtils.endsWith(null, null));
}
}

Explanation

  1. string = "educative"
    suffix = "tive"

    The function returns true since the string ends with the suffix.

  2. string = "educative"
    suffix = "edu"

    The function returns false since the string does not end with the suffix.

  3. string = "educative"
    suffix = null

    The function returns false because the suffix is null.

  4. string = null
    suffix = null

    The function returns true because the string and the suffix are null.

Output

The output of the code will be as follows:


true
false
false
true

RELATED TAGS

java
Did you find this helpful?