Java String endsWith(String suffix)
method checks whether the String
ends with a specified suffix. This method returns a boolean value true or false. If the specified suffix is found at the end of the string then it returns true else it returns false.
The endsWith() Method Signature:
public boolean endsWith(String suffix)
Java String endsWith() Method example
In the following example we have two strings str1
and str2
and we are checking whether the strings are ending with the specified suffixes.
public class EndsWithExample{ public static void main(String args[]){ String str1 = new String("This is a test String"); String str2 = new String("Test ABC"); boolean var1 = str1.endsWith("String"); boolean var2 = str1.endsWith("ABC"); boolean var3 = str2.endsWith("String"); boolean var4 = str2.endsWith("ABC"); System.out.println("str1 ends with String: "+ var1); System.out.println("str1 ends with ABC: "+ var2); System.out.println("str2 ends with String: "+ var3); System.out.println("str2 ends with ABC: "+ var4); } }
Output:
str1 ends with String: true str1 ends with ABC: false str2 ends with String: false str2 ends with ABC: true
String endsWith() method with if statement
Since the method endsWith() returns a boolean value, it can be used in a If statement as a condition as shown in the following example. Here we have given a String “Java String tutorial” and we are checking inside if statement whether the string ends with suffix “tutorial” or not.
public class JavaExample { public static void main(String[] args) { String str = "Java String tutorial"; if(str.endsWith("tutorial")) { System.out.println("The Given String ends with tutorial"); } } }
Output:
Rafael says
Hello, I have question connected with this Example.
Is there easy way to check whether String is ending with 5 digits (ex. “21311” “24444” “52211”), but we don’t know digits, in the way you are showing on example above? I need to use it in my filterin method to leave only numbers in String, using Java 8 stream.
Greetings, Rafael.