Java – Check if this String Ends with a Specific Substring
To check if this String ends with a string, you can use String.endsWith() function, or you can use some other ways.
In this tutorial, we will go through different processes to know some of the possible ways of checking if this string ends with a specific string.
First we shall see the standard way of using String.endsWith() function.
The syntax of endsWith() function is as follows.
String.endsWith(String str)
endsWith() function checks if this string ends with the string passed as argument to the function.
Following are some of the quick examples of endsWith().
"tutorialkart".endsWith("kart"); //true
"tutorialkart".endsWith("tuto"); //false
"tutorialkart".endsWith("t"); //true
"tutorialkart".endsWith("ia"); //false
Let us dive into some Java programs that demonstrate different ways to check if this string ends with a string.
Example 1 – Check If String Ends with a Substring – String.endsWith()
In this example, we have taken two strings: str1 and str2. After that we shall check if str1 ends with str2 using String.endsWith() method.
CheckIfStringEndsWith.java
/**
* Java Example Program to Check if String Ends with a String
*/
public class CheckIfStringEndsWith {
public static void main(String[] args) {
String str1 = "www.tutorialkart.com";
String str2 = "com";
boolean b = str1.endsWith(str2);
System.out.print(b);
}
}
Run the above program and you should get the following output in console.
Output
true
Example 2 – Check If String Ends with a Substring
In this example, we have written a custom function, to check if a string ends with the specified string.
CheckIfStringEndsWith2.java
/**
* Java Example Program to Check if String Ends with
*/
public class CheckIfStringEndsWith2 {
public static void main(String[] args) {
System.out.println(ifEndsWith("www.tutorialkart.com", "com"));
System.out.println(ifEndsWith("www.tutorialkart.com", "www"));
}
/**
* Checks if str1 ends with str2
* @param str1
* @param str2
* @return return true if str1 ends with str2, else return false
*/
public static boolean ifEndsWith(String str1, String str2) {
if(str1.length()>=str2.length()) {
if(str1.substring(str1.length()-str2.length(), str1.length()).equals(str2)) {
return true;
}
}
return false;
}
}
Run the program.
Output
true
false
Conclusion
In this Java Tutorial, we learned how to check if a String ends with another string.