Skip to content

Check if String ends with another String in Java example

This Java example shows how to check if string ends with another string using the endsWith method, using the regular expression or by doing case insensitive comparison.

How to check if a string ends with another string in Java?

You can use the endsWith method of the String class to check.

The endsWIth method returns true if the string ends with the argument string,empty false otherwise.

Output

Note:

The endsWith method always returns true for empty string or if the string is equal to the argument string. For example,

Output

How to check if the string ends with any of the given strings?

1) Using the OR operator

Suppose you want to check if the string ends with any of the given multiple string values. Since the endsWith method accepts only one argument, you need to check it multiple times using OR (||) operator as given below.

Output

2) Using the Regular Expression

You can also use a regular expression to check the same as given below.

Output

We have used the "^.*(\\.txt|\\.rtf)$" pattern to check if the file name ends with “.txt” or “.rtf” file extensions, where

A dot (.) has a special meaning in the regular expression (it matches any character). Hence, in order to do a literal search of a dot in a string, we need to escape it like “\\.”.

3) Using the Apache Commons library

If you are using the Apache Commons library, you can use the endsWithAny method of the StringUtils class to check if the string ends with any of the given multiple strings as given below.

Output

How to check using case insensitive comparison?

By default, the endsWith method is case sensitive. For example,

will return “false”.

You can use the toLowerCase (or the toUpperCase) method to change the case of the both the strings as given below.

Output

If you are using the Apache Commons library, you can use the endsWithIgnoreCase method of the StringUtils class to do case insensitive comparison as given below.

Output

This example is a part of the String in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.