How do I check a string ends with a specific word?

The String.endsWith() method can be used to check if a string ends with a specific word. It will return a boolean true if the suffix is found at the end of the string object.

In this example we will start the code by creating a class called StringEndsWithExample. This class has a standard main() method that makes the class executable. In the main() method we create a string variable called str and assign a text to it.

On the following line you can see an if conditional statement to check it the str string ends with "lazy dog". If it ends with that words then the corresponding block in the if statement will be executed.

package org.kodejava.lang;

public class StringEndsWithExample {
    public static void main(String[] args) {
        String str = "The quick brown fox jumps over the lazy dog";

        // well, does the fox jumps over a lazy dog?
        if (str.endsWith("lazy dog")) {
            System.out.println("The dog is a lazy dog");
        } else {
            System.out.println("Good dog!");
        }

        // Ends with empty string.
        if (str.endsWith("")) {
            System.out.println("true");
        }

        // Ends with the same string.
        if (str.endsWith(str)) {
            System.out.println("true");
        }
    }
}

Another thing that you need to know is that the endsWith() method will return true if you pass in an empty string or another string that is equals to this string as the argument. This method is also case-sensitive.

When you run the code snippet above you can see the following lines printed out:

The dog is a lazy dog
true
true
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.