Skip to content

Check if String starts with another String in Java example

This Java example shows how to check if string starts with another string using the startsWith method, using a regular expression or using case insensitive comparison.

How to check if the string starts with another string in Java?

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

The startsWIth method returns true if the string starts with the specified string, false otherwise.

Output

Note:

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

Output

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

1) Using OR operator

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

Output

2) Using a regular expression

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

Output

We have used the “^(Sat|Sun).*$” pattern to check if the day starts with the string “Sat” or “Sun”, where

3) Using the Apache Commons library

If you are using the Apache Commons library, you can use the startsWithAny method of the StringUtils class to check as given below.

Output

How to check using case insensitive comparison?

By default, the startsWith is case sensitive. For example,

will return “false”.

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

Output

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

Output

This example is a part of the Java String 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.