What is StringUtils.endsWith in Java?
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:
- The method returns
truewhen the input string and the suffix arenull. Twonullreferences are considered to be equal. - The method returns
falsewhen the input string or the suffix isnull.
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 checkfinal 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
-
string =
"educative"
suffix ="tive"The function returns
truesince the string ends with the suffix. -
string =
"educative"
suffix ="edu"The function returns
falsesince the string does not end with the suffix. -
string =
"educative"
suffix =nullThe function returns
falsebecause the suffix isnull. -
string =
null
suffix =nullThe function returns
truebecause the string and the suffix arenull.
Output
The output of the code will be as follows:
true
false
false
true