When working with strings in Java, one of the most common tasks is to check whether a given string contains a specific sequence of characters. Java provides a very handy method for this: the contains()
method.
In this blog, we will explore the contains()
method in Java, its syntax, how it works, code examples, common use cases, and important things to keep in mind. By the end, you’ll be able to confidently use contains()
in your projects.
What is the contains() Method?
The contains()
method is a built-in method of the Java String
class that checks whether a given sequence of characters exists within a string.
It returns a boolean value:
-
true
→ if the string contains the specified sequence. -
false
→ if it does not.
Syntax of contains()
public boolean contains(CharSequence sequence)
Parameters:
-
sequence → The character sequence (like a
String
,StringBuilder
, orStringBuffer
) that you want to search for inside the main string.
Return Type:
- Returns true if the sequence exists, otherwise false.
Example 1: Basic Usage of contains()
public class ContainsExample {
public static void main(String[] args) {
String text = "Java programming is fun";
System.out.println(text.contains("Java")); // true
System.out.println(text.contains("Python")); // false
System.out.println(text.contains("fun")); // true
}
}
Output:
true
false
true
Here, the method checks whether "Java"
, "Python"
, and "fun"
exist in the string.
Example 2: Case Sensitivity
The contains()
method is case-sensitive.
public class CaseSensitiveExample {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(text.contains("Hello")); // true
System.out.println(text.contains("hello")); // false
}
}
Output:
true
false
If you want a case-insensitive search, you can convert both strings to lowercase or uppercase using .toLowerCase()
or .toUpperCase()
.
text.toLowerCase().contains("hello".toLowerCase()); // true
Example 3: Using contains() with Variables
public class VariableExample {
public static void main(String[] args) {
String mainString = "Welcome to Java tutorials";
String searchWord = "Java";
if (mainString.contains(searchWord)) {
System.out.println("Found: " + searchWord);
} else {
System.out.println("Not Found");
}
}
}
Output:
Found: Java
Common Use Cases of contains()
- Search Functionality
- Check if user input contains a certain keyword.
- Validation
- Verify whether an email contains
"@"
. - Ensure a URL contains
"https"
.
- Filtering Data
- Filter strings in a list based on keywords.
Example: Filtering with contains()
import java.util.*;
public class FilterExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
for (String name : names) {
if (name.contains("a") || name.contains("A")) {
System.out.println(name);
}
}
}
}
Output:
Alice
Charlie
David
Limitations of contains()
- Case Sensitivity – By default, it doesn’t ignore uppercase/lowercase differences.
-
Exact Sequence Match – It looks for exact character sequences, not patterns (use regex with
matches()
if you need pattern matching). -
NullPointerException – If the input sequence is
null
, it throws an exception.
Difference Between contains() and Other Methods
Method | Description | Example |
---|---|---|
contains() |
Checks if a sequence exists | "Hello".contains("He") → true |
equals() |
Compares entire strings | "Hello".equals("hello") → false |
startsWith() |
Checks if string starts with prefix | "Hello".startsWith("He") → true |
endsWith() |
Checks if string ends with suffix | "Hello".endsWith("lo") → true |
matches() |
Uses regex for pattern matching | "abc123".matches("[a-z]+\\d+") → true |
Best Practices
- Use
contains()
for simple substring checks. - For case-insensitive checks, convert both strings to lowercase.
- For pattern matching, prefer regex with
matches()
orPattern
. - Always check for
null
values before callingcontains()
to avoid exceptions.
Conclusion
The Java String Contains method in Java is a powerful and straightforward tool to check if a string includes a particular sequence of characters. It is widely used in text searching, data filtering, and validation tasks.
Key takeaways:
- It returns true/false based on substring presence.
- It is case-sensitive.
- Works with CharSequence types (
String
,StringBuilder
,StringBuffer
). - Perfect for simple searches, but not for complex patterns.
By mastering the contains()
method, you can make your string operations in Java much more efficient and effective.
Top comments (0)