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.
1 |
public boolean contains(CharSequence ch) |
This method returns true if the string contains the specified character sequence.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.stringexamples; public class StringContainsExample { public static void main(String[] args) { String str1 = "Hello world"; String strSearch = "world"; boolean doesContain = str1.contains(strSearch); System.out.println(doesContain); } } |
Output
1 |
true |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringexamples; import org.apache.commons.lang3.StringUtils; public class StringContainsExample { public static void main(String[] args) { String str1 = "Hello world"; String strSearch = "world"; boolean doesContain = StringUtils.contains(str1, strSearch); System.out.println(doesContain); } } |
Output
1 |
true |
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.
1 2 3 4 5 |
String str1 = "Hello world"; String strSearch = "HELLO"; boolean doesContain = str1.contains(strSearch); System.out.println(doesContain); |
Output
1 |
false |
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.
1 2 3 4 5 6 |
String str1 = "Hello world"; String strSearch = "HELLO"; boolean doesContain = str1.toLowerCase().contains( strSearch.toLowerCase() ); System.out.println(doesContain); |
Output
1 |
true |
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.
1 2 3 4 5 6 |
String str1 = "Hello world"; String strSearch = "HELLO"; boolean doesContain = StringUtils.containsIgnoreCase(str1, strSearch); System.out.println(doesContain); |
Output
1 |
true |
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.