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:
true
when the input string and the suffix are null
. Two null
references are considered to be equal.false
when the input string or the suffix is null
.Note: For case-insensitive comparison, use StringUtils.endsWithIgnoreCase.
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;
public static boolean endsWith(final CharSequence str, final CharSequence suffix)
The function takes in two parameters:
final CharSequence str
: the character sequence to checkfinal CharSequence suffix
: the suffix to find in the stringThe function returns true
if the string ends with the suffix. Otherwise, it returns false
.
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));}}
string = "educative"
suffix = "tive"
The function returns true
since the string ends with the suffix.
string = "educative"
suffix = "edu"
The function returns false
since the string does not end with the suffix.
string = "educative"
suffix = null
The function returns false
because the suffix is null
.
string = null
suffix = null
The function returns true
because the string and the suffix are null
.
The output of the code will be as follows:
true
false
false
true