What is the use of the Java String endsWith() method?

In this tutorial, we will learn about the endsWith()  in Java with the example.
Many string methods in Java can be used when we require a proposed output. In this tutorial, we going to learn in brief about the endsWith() method with an example that will be helpful to get your required output.

Java String endsWith() method

Definition:

The endsWith() method will check whether a string ends with a specified character(s). It will consider case sensitivity.
(Note: specified character(s) will be provided by us to check whether the string ends with the given character(s) or not.)
It will return the output as True or False.

Syntax of ‘endsWith()’:

public boolean endsWith(String chars) 
- where chars are checked with the input string.

Example of demonstrating the use of  ‘endsWith()’ in Java:

Enlightenerclass EM {
    public static void main(String[] args) {
       String ex = "EndsWithExample";
         System.out.println(ex.endsWith("mple"));     //TRUE
         System.out.println(ex.endsWith("Example"));  //TRUE
         System.out.println(ex.endsWith("example"));  //FALSE
         System.out.println(ex.endsWith("abcdef"));     //FALSE
    }
}

 

Output of the following code:

true
true
false
false

Conclusion:

In this example:

  1. ex.endsWith(“mple”)  will check if the string “EndsWithExample” ends with “mple”, which returns true .
  2. ex.endsWith(“Example”)  will check if the string “EndsWithExample” ends with “Example” which returns true.
  3. ex.endsWith(“example”)  will check if the string “EndsWithExample” ends with “example”, which returns false.
  4. ex.endsWith(“abcdef”)  will check if the string “EndsWithExample” ends with “abcdef”, which returns false.

We get the 3rd output false because character ‘e’ of “example” in String “EndsWithExample” is Capital.
So this is how the endswith() checks the characters ending with specified characters or not.

 

You can refer other java methods ‘startWith()’  in Java which will  check whether a string starts with a specified character(s) or not rather then ending.

 

Leave a Comment

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

Scroll to Top