Skip to content

Java String Contains Example

Java String Contains Example shows how to check if the String contains another String using the contains method. The example also shows whether the contains method is case sensitive or not.

How to check if String contains another String in Java?

To check if String contains another String, you can use the contains method of the String class.

This method returns true if the string contains the specified character sequence.

Example

Output

Note: The contains method does not accept a regular expression as an argument. If you want to use a regular expression, you can use the matches method of String class.

If you are using the Apache Commons library, you can use the contains method of the StringUtils class to check if the string contains another String as given below.

Output

Is Java String contains method case sensitive?

Yes, the string contains method is case sensitive. Let’s have a look at the below code snippet.

Output

In order to do case insensitive contains search or ignore case, you need to make both the strings to either upper case or lower case before calling the method as given below.

Output

If you are using the Apache Commons library, you can use the containsIgnoreCase method of the StringUtils class to make case insensitive contains comparison or to ignore case as given below.

Output

Note: If you want to check if the string contains a number, please check out the check if String contains a number example.

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.