Groovy - String endsWith() method
endsWith() method tests whether this string ends with the specified suffix.
Syntax
Boolean endsWith(String suffix)
Parameters
suffix − The suffix to search for.
Return Value
This method returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object as determined by the equals(Object) method.
Example - Checking if String Ends with Given Suffix
Following is an example of the usage of endsWith() method. If the given string value is the same as the specified suffix, the endsWith() method returns true.
Example.groovy
class Example {
static void main(String[] args) {
//instantiate a string class
String str = new String("Hello");
//initialize the suffix
String suffix = "llo";
println("The given string is: " + str);
println("The suffix is: " + suffix);
//using the endsWith() method
println("The string ends with the specified suffix or not? " + str.endsWith(suffix));
}
}
Output
When we run the above program, we will get the following result −
The given string is: Hello The suffix is: llo The string ends with the specified suffix or not? true
Example - Checking if String is not Ending with Given Suffix
Following is an example of the usage of endsWith() method. If the given string value is different from the specified suffix, the endsWith() method returns false.
Example.groovy
class Example {
static void main(String[] args) {
// create an object of the string class
String str = new String("Groovy Programming");
// initialize the suffix
String suffix = "Groovy";
System.out.println("The given string is: " + str);
System.out.println("The suffix is: " + suffix);
// using the endsWith() method
System.out.println("The string ends with the specified suffix or not? " + str.endsWith(suffix));
}
}
Output
When we run the above program, we will get the following result −
The given string is: Groovy Programming The suffix is: Groovy The string ends with the specified suffix or not? false
Example - Checking if String is Ending with Given Suffix in Case Sensitive Way
Following is an example of the usage of endsWith() method. If the given string value is the same as the suffix, but the case is different, the endsWith() method returns false.
Example.groovy
class Example {
static void main(String[] args) {
//instantiate the string class
String str = new String("TutorialsPoint");
//initialize the suffix
String suffix = "point";
println("The given string is: " + str);
println("The suffix is: " + suffix);
//using the endsWith() method
println("The string ends with the specified suffix or not? " + str.endsWith(suffix));
}
}
Output
When we run the above program, we will get the following result −
The given string is: TutorialsPoint The suffix is: point The string ends with the specified suffix or not? false