The Java String endsWith() method takes an argument or a parameter and returns a boolean value(true or false).

Sting endsWith():

The String endsWith() method checks whether the string ends with that specific char sequence or not. It also considers a case of a string. If both strings are ending with the same value, but the case is not the same, the method will return false. The best solution for this problem is to convert both strings in lower case or in upper case. Like this, the case of both strings will become the same.

Method signature:

The signature for an endsWith() method is as shown below.

public boolean endsWith(String str)

Method parameters and return type:

Return type: It returns a boolean value(true or false).

Parameters: It takes a string as a parameter.

Throws: It throws NullPointerException if the passed string is null.

Java String endswith():

Example 1:

In this example, we have initialized a string and checked whether the string ends with “tutorial” and “Java” char sequences.

Source code:

public class Example1 {
    
    public static void main(String[] args) {
        String str = "This is Java tutorial";
        System.out.println(str.endsWith("tutorial"));
        System.out.println(str.endsWith("Java"));
    }
}

Output:

run:
true
false
BUILD SUCCESSFUL (total time: 0 seconds)

Example 2:

Here is another example that explains how you can use endsWith() method in Java. Here we have used endsWith() with conditional statements. Basically, we have initialized two strings and we have compared their ending char sequence.

Source code:

public class Example2 {
    
    public static void main(String[] args) {
        String str1 = "Welcome to online tutorial point";
        String str2= "This is online tutorial point";
        
        if(str1.endsWith("point") && str2.endsWith("point")){
            System.out.println("End of strings is equal");
        } else{
            System.out.println("End of strings is not equal");
        }
    }
}

Output:

run:
End of strings is equal
BUILD SUCCESSFUL (total time: 0 seconds)

Example 3:

In this example, we have used an array of strings. We have checked for the animal names that end with “g.” You can use this logic in your programs for performing different tasks.

Source code:

public class Example3 {
    
    public static void main(String[] args) {
        
        String strArray[] = {"Dog", "Cat", "frog", "Donkey"};
        
        for(int i=0; i<strArray.length; i++){
            if(strArray[i].endsWith("g")){
                System.out.println("True");
            } else {
                System.out.println("False");
            }
        }
    }
}

Output:

run:
True
False
True
False
BUILD SUCCESSFUL (total time: 0 seconds)

References:

Happy Learning 🙂