Working with strings is one of the most common tasks in Java programming. Whether you are building a simple utility or a large-scale application, you will often need to check if a string contains a particular sequence of characters. Fortunately, Java provides a very handy method called contains() in the String class that makes this task straightforward.
In this blog, we’ll explore the Java String contains() method in detail, break down its syntax, discuss its return value, and go through multiple practical examples. By the end, you’ll know exactly how to use this method effectively in your projects.
What is the contains() Method?
The contains() method in Java is a member of the String class, which resides in the java.lang package. It is used to check if a sequence of characters exists inside a given string. If the string contains the specified sequence, the method returns true; otherwise, it returns false.
Syntax:
public boolean contains(CharSequence sequence)
Parameter: Accepts a CharSequence (like String, StringBuilder, or StringBuffer).
Return Type: Returns a boolean value.
Case Sensitivity: The method is case-sensitive, meaning "Hello" is different from "hello".
Simple Example
Let’s start with a very basic example:
public class ContainsExample {
public static void main(String[] args) {
String text = "Java programming is powerful and easy to learn.";
// Check if the string contains "powerful"
boolean result = text.contains("powerful");
System.out.println("Does the text contain 'powerful'? " + result);
}
}
Output:
Does the text contain 'powerful'? true
In this example, since the word "powerful" is present in the string, the method returns true.
Case Sensitivity in contains()
One important thing to note is that the contains() method is case-sensitive.
public class CaseExample {
public static void main(String[] args) {
String text = "Java is Fun";
System.out.println(text.contains("Java")); // true
System.out.println(text.contains("java")); // false
}
}
Here, the first check returns true because "Java" matches exactly, while the second check returns false because "java" doesn’t match the case.
If you want a case-insensitive search, you can convert both strings to lowercase or uppercase before comparing:
text.toLowerCase().contains("java".toLowerCase());
Using contains() with Conditions
The contains() method is often used in conditional statements to make decisions.
public class ConditionExample {
public static void main(String[] args) {
String email = "user@example.com";
if (email.contains("@")) {
System.out.println("Valid email format.");
} else {
System.out.println("Invalid email format.");
}
}
}
Output:
Valid email format.
This is a very practical use case where you can check if a string follows a basic pattern.
Real-World Example: Filtering Data
Imagine you are building a search feature in your application. You can use the contains() method to filter results.
import java.util.ArrayList;
import java.util.List;
public class SearchExample {
public static void main(String[] args) {
List products = new ArrayList<>();
products.add("Laptop");
products.add("Smartphone");
products.add("Smartwatch");
products.add("Tablet");
String keyword = "Smart";
System.out.println("Search results for: " + keyword);
for (String product : products) {
if (product.contains(keyword)) {
System.out.println(product);
}
}
}
}
Output:
Search results for: Smart
Smartphone
Smartwatch
Here, the contains() method helps us display only those products that match the user’s search keyword.
Using contains() with StringBuilder and StringBuffer
Since the parameter of contains() accepts a CharSequence, you can also pass StringBuilder or StringBuffer objects.
public class BuilderExample {
public static void main(String[] args) {
String text = "Learning Java can be fun.";
StringBuilder sb = new StringBuilder("Java");
StringBuffer sf = new StringBuffer("fun");
System.out.println(text.contains(sb)); // true
System.out.println(text.contains(sf)); // true
}
}
This flexibility makes the method more versatile.
Common Mistakes with contains()
Forgetting about case sensitivity – "Java".contains("java") will return false.
Using regex mistakenly – The contains() method does not accept regular expressions. If you need regex, you should use the matches() method instead.
NullPointerException – If you call contains() on a null string, it will throw an exception. Always check if the string is not null before calling it.
Difference Between contains() and Other Methods
contains() vs equals()
contains() checks if a sequence of characters exists.
equals() checks if two strings are exactly the same.
contains() vs indexOf()
contains() returns a boolean.
indexOf() returns the index of the substring if found, or -1 if not found.
Example:
String text = "Java is amazing";
System.out.println(text.contains("Java")); // true
System.out.println(text.indexOf("Java")); // 0
Practical Use Cases
Search functionality – Filtering data in a search bar.
Validation – Checking if an email contains "@".
Security checks – Detecting suspicious words in user input.
Parsing text – Identifying keywords in documents or logs.
Performance Considerations
The contains() method is efficient for most common tasks, but if you are working with very large strings or performing millions of checks, you might want to consider alternative approaches like regex matching, Apache Commons StringUtils, or indexing.
Conclusion
The Java String contains() method is a simple yet powerful tool when working with strings. It allows you to check if a sequence of characters exists inside another string, making it useful for validation, searching, and filtering tasks. Remember that it is case-sensitive, so you may need to convert strings to lowercase or uppercase for case-insensitive checks.
By practicing with different examples and real-world scenarios, you’ll become comfortable using this method in your projects. Whether you’re validating an email, building a search bar, or scanning logs, the contains() method is one of the first tools you’ll reach for.
So the next time you need to check if a string holds a particular value, just remember the power of Java String Contains. With a clear understanding of this method, you can write cleaner, more efficient, and more reliable code.
Top comments (0)