endsWith() Java - check whether a string ends with a specified suffix
The endsWith() method checks whether a string ends with a specified suffix, value, etc.
Syntax:
1 |
public boolean endsWith(String suffix) |
How To Call the Method:
1 |
boolean b = str.endsWith("some string"); |
Example:
1 2 3 4 5 6 7 8 9 10 |
public class Test { public static void main(String args[]) { String line = "Good morning"; boolean b1 = line.endsWith("morning"); boolean b2 = line.endsWith("evening"); System.out.println("String " + line + " ends with 'morning'? " + b1); System.out.println("String " + line + " ends with 'evening'? " + b2); } } |
If you run this code on your computer, you will see the following in the console:
Commentary:
There is a string "Good morning"
- With the help of endsWith() we checked whether the string ends with "morning". Yes, it ends with "morning", that's why we've got "true" in the console.
- With the help of endsWith() we checked whether the sting ends with "evening". No, it doesn't end with evening, that's why we've got "false" in the console.
Please note, that if we add any character, for example an exclamation mark after the word "morning", then we'll get "false" in the console.
That's it for this article. You can find more articles in our Java Tutorial for Beginners.