Java String endsWith() Method

In this topic, we will learn how to use endsWith(String suffix) method in Java program. this method is under java.lang package and it exists in String class.

This method uses to check whether the string ends with a specific suffix or specific substring or not. this method returns boolean value true if the substring exists at the end of the string and returns false if the substring does not exist at the end of string.

Also read: Add Suffix to array elements in Java

Signature:

public boolean endsWith(String suffix)

parameter:

suffix- specified suffix part

Return type:

boolean (true or false)

Example Program: Java String endsWith() Method

package codespeedy;

import java.util.*;
public class Codespeedy {

    public static void main(String[] args) {
       String str="Welcome codespeedy tutorial"; // declare string 
       System.out.println(str.endsWith("tutorial"));   // check whether "tutorial" is suffix of string or not
       System.out.println(str.endsWith("al"));         // check whether "al" is suffix of string or not
       // codespeedy is exists in the string but it is not at the end it will return false
       System.out.println(str.endsWith("codespeedy"));  // check whether "codespeedy" is suffix of string or not 
       System.out.println(str.endsWith("l"));          // check whether "l" is suffix of string or not
    }
    
}

output:

true
true
false
true

Analyze the output:

str= "Welcome to codespeedy tutorial"
1- str.endsWith("tutorial");  it will show true because tutorial is the suffix of string
2-  str.endsWith("al");      it will show true because "al" is the suffix of string
3- str.endsWith("codespeedy");    it will show false because "codespeedy" is substring but not the ending substring (suffix).
4- str.endsWith("l");   it will show true because "l" is suffix of the string .

Leave a Reply

Your email address will not be published. Required fields are marked *