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

The String.endsWith() method can be use to check if a string ends with a specific word. It will returns 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.example.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("")) {

        // Ends with the same string.
        if (str.endsWith(str)) {

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

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply