Java String contains() Method Explained with Examples
When working with strings in Java, developers often need to check if a particular word or sequence of characters exists within a larger string. Java provides a very handy method for this: the Java string contains() method. This blog will explain what the method is, how it works, and where you can use it in real-world projects.
What is the contains() Method in Java?
The contains() method belongs to the String class in Java. It is used to check whether a specific sequence of characters (a substring) exists inside a given string.
It returns a boolean value:
true → if the substring is found.
false → if the substring is not found.
Since strings are widely used in Java programs (user inputs, database values, file content), this method becomes extremely useful for quick searches and validations.
Syntax of contains()
public boolean contains(CharSequence sequence)
Parameters:
sequence → The substring you want to search for.
Return Value:
true if the string contains the given sequence.
false otherwise.
Simple Example of contains()
public class ContainsExample { public static void main(String[] args) { String text = "Welcome to Java Programming"; System.out.println(text.contains("Java")); // true System.out.println(text.contains("Python")); // false } }
Output:true false
Here, the string contains the word "Java", so it returns true, while "Python" is not found, so it returns false.
Important Points About contains()
Case-sensitive → "Java".contains("java") will return false.
Checks sequence, not word → "Programming".contains("gram") will return true.
Null values not allowed → Passing null will throw NullPointerException.
Uses CharSequence → Works with classes that implement CharSequence (like StringBuilder, StringBuffer).
Case-Sensitive Example
public class CaseSensitiveExample { public static void main(String[] args) { String text = "Hello Java"; System.out.println(text.contains("Java")); // true System.out.println(text.contains("java")); // false } }
Using contains() with Conditional Statements
The contains() method is often used in if-else conditions for validations.public class LoginExample { public static void main(String[] args) { String email = "[email protected]"; if (email.contains("@gmail.com")) { System.out.println("Valid Gmail Address"); } else { System.out.println("Invalid Email"); } } }
Output:Valid Gmail Address
This is useful for checking domain names in emails, validating URLs, or filtering input values.
Practical Examples of contains()
1. Checking for Keywords in Text
String article = "Java is one of the most popular programming languages."; System.out.println(article.contains("popular")); // true
2. Filtering Search Results
Imagine you are building a search bar:String[] products = {"Laptop", "Keyboard", "Mouse", "Laptop Stand"}; for (String item : products) { if (item.contains("Laptop")) { System.out.println(item); } }
Output:Laptop Laptop Stand
3. Using contains() with StringBuilder
Since contains() accepts CharSequence, you can use it with StringBuilder too.StringBuilder sb = new StringBuilder("Java Tutorial"); System.out.println("Result: " + sb.toString().contains("Tutorial")); // true
Common Interview Questions on contains()
Q1: Is contains() case-sensitive in Java? Yes, it is case-sensitive. Use toLowerCase() or equalsIgnoreCase() for case-insensitive checks.
Q2: Can you use contains() with regular expressions? No, contains() only checks for plain text. For regex, use matches() or Pattern class.
Q3: What happens if you pass null to contains()? It throws a NullPointerException.
Q4: Difference between contains() and equals()? contains() checks if a substring exists. equals() checks if two strings are exactly the same.
Alternative Approaches to contains()
Sometimes you may need more advanced checks. Here are alternatives:
Using indexOf()
String str = "Java Programming"; System.out.println(str.indexOf("Java") != -1); // true
Using regex
System.out.println("Hello123".matches(".*123.*")); // true
Real-World Use Cases
Form validation – Check if input contains required keywords.
Search engines – Match user queries with stored data.
Spam filters – Detect banned words in messages.
Log analysis – Identify specific error messages in system logs.
Best Practices
Always check for null values before using contains().
For case-insensitive checks, convert both strings to lowercase.
Avoid using contains() for complex patterns → prefer regex.
Use contains() in filters and loops for better readability.
Conclusion
The Java String contains() method is a simple yet powerful tool for searching substrings within a string. It plays an important role in text validation, filtering, and search-related tasks. As a fresher preparing for interviews, understanding how contains() works, its case sensitivity, and real-world applications will give you an edge.
By practicing the examples shared here, you’ll not only master this method but also improve your confidence in handling string-related questions during interviews.
















