How to Check if String Contains Substring in Java
In Java, you can check if a string contains a substring using the
contains() method of the String class. It returns true if the substring is found and false otherwise.Syntax
The contains() method is called on a string object and takes one argument: the substring to search for. It returns a boolean value.
string.contains(substring): Returnstrueifsubstringis insidestring.
java
boolean result = string.contains(substring);Example
This example shows how to use contains() to check if a string has a certain substring and prints the result.
java
public class Main { public static void main(String[] args) { String text = "Hello, welcome to Java programming!"; String word1 = "Java"; String word2 = "Python"; System.out.println("Does the text contain '" + word1 + "'? " + text.contains(word1)); System.out.println("Does the text contain '" + word2 + "'? " + text.contains(word2)); } }
Output
Does the text contain 'Java'? true
Does the text contain 'Python'? false
Common Pitfalls
One common mistake is confusing contains() with case-insensitive search. The contains() method is case-sensitive, so "java" and "Java" are different.
To check ignoring case, convert both strings to the same case first.
java
public class Main { public static void main(String[] args) { String text = "Hello, welcome to Java programming!"; String search = "java"; // Wrong: case-sensitive check System.out.println(text.contains(search)); // false // Right: convert both to lower case System.out.println(text.toLowerCase().contains(search.toLowerCase())); // true } }
Output
false
true
Quick Reference
| Method | Description | Returns |
|---|---|---|
| contains(CharSequence s) | Checks if string contains the sequence s | boolean (true/false) |
| toLowerCase() | Converts string to lower case | String |
| toUpperCase() | Converts string to upper case | String |
Key Takeaways
Use
string.contains(substring) to check if a substring exists in a string.contains() is case-sensitive; convert strings to lower or upper case for case-insensitive checks.The method returns a boolean:
true if found, false if not.Always handle null strings carefully to avoid errors when calling
contains().