The String.contains() method checks whether a string contains a specified sequence of characters, returning a boolean result (true or false).
CharSequence Matching & Clean Conditionals: Because it accepts any CharSequence, you can check strings, StringBuilder, or StringBuffer directly. To retrieve the numeric index position of a match, see indexOf(). For prefix and suffix matching, explore startsWith() and endsWith(). For case-insensitive checking, normalize with toLowerCase().
The contains() method is defined in java.lang.String:
// Formal signature of String.contains() in java.lang.String
public boolean contains(CharSequence s)
| Parameter / Element | Type | Description & Operational Rule |
|---|---|---|
s |
CharSequence |
The character sequence to search for (e.g. String, StringBuilder, StringBuffer). |
| Return Value | boolean |
Returns true if the sequence is found inside the string; false otherwise. |
| Exception | Runtime | Throws NullPointerException if the argument s is null. |
Searching for words, characters, or substrings returns a simple boolean true or false:
String my_str = "Welcome to plus2net";
System.out.println(my_str.contains("2")); // true
System.out.println(my_str.contains("net")); // true
System.out.println(my_str.contains("plus2net")); // true
System.out.println(my_str.contains("co")); // true (in 'Welcome')
System.out.println(my_str.contains("no")); // falseTerminal Output:
true
true
true
true
false
Because the method accepts CharSequence, you can check mutable buffers without calling .toString():
String target = "Java Programming Guide";
// 1. Passing a standard String
System.out.println(target.contains("Java")); // true
// 2. Passing a StringBuilder directly (polymorphic CharSequence)
StringBuilder sb = new StringBuilder("Programming");
System.out.println(target.contains(sb)); // true
// 3. Passing a StringBuffer directly
StringBuffer sbf = new StringBuffer("Guide");
System.out.println(target.contains(sbf)); // trueTerminal Output:
true
true
true
Understanding when to use boolean presence checking versus numeric index retrieval improves code clarity:
| Feature | str.contains(target) |
str.indexOf(target) |
|---|---|---|
| Return Type | boolean (true or false). |
int (0-based index or -1). |
| Primary Purpose | Simple condition testing in if statements. |
Extracting coordinates for slicing or splitting. |
| Readability | High: expresses intent directly (if (s.contains(...))). |
Requires relational guard (if (s.indexOf(...) != -1)). |
String email = "support@plus2net.com";
// contains(): Clean, direct boolean check
if (email.contains("@")) {
System.out.println("Valid email: contains '@' symbol.");
}
// indexOf(): Used when the actual character position is needed
int atPos = email.indexOf("@");
if (atPos != -1) {
System.out.println("'@' symbol found at index: " + atPos);
}Terminal Output:
Valid email: contains '@' symbol.
'@' symbol found at index: 6
contains() is strictly case-sensitive. To search case-insensitively, normalize both strings with toLowerCase():
String text = "Java is powerful";
String query = "JAVA";
// 1. Direct contains(): Case-sensitive (returns false)
System.out.println("Direct check: " + text.contains(query)); // false
// 2. Lowercase normalization: Case-insensitive (returns true)
boolean found = text.toLowerCase().contains(query.toLowerCase());
System.out.println("Normalized lowercase: " + found); // trueTerminal Output:
Direct check: false
Normalized lowercase: true
Passing null as the argument to contains() throws a NullPointerException. Guard against crashes with null-check validation:
String input = "plus2net";
String needle = null;
// RISKY: Passing null throws NullPointerException immediately
try {
System.out.println(input.contains(needle));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null needle!");
}
// SAFE APPROACH: Guard against null on both source and target
boolean safeCheck = (input != null && needle != null) && input.contains(needle);
System.out.println("Safe check result: " + safeCheck); // falseTerminal Output:
Caught NullPointerException on null needle!
Safe check result: false
In community applications and form submissions, validating user input against a list of prohibited words is a common task:
public class ContentModerator {
private static final String[] BLOCKED_WORDS = {"spam", "viagra", "casino", "scam"};
public static boolean containsBlockedContent(String comment) {
if (comment == null) return false;
String clean = comment.toLowerCase();
for (String badWord : BLOCKED_WORDS) {
if (clean.contains(badWord)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println("Comment 1: " + containsBlockedContent("Great tutorial on Java!")); // false
System.out.println("Comment 2: " + containsBlockedContent("Visit our CASINO online!")); // true
}
}Terminal Output:
Comment 1: false
Comment 2: true
Calling str.contains("") always evaluates to true for any non-null string, because every string conceptually contains the empty sequence.
contains() searches for exact literal characters. Passing regex patterns like str.contains("\d+") searches for literal backslashes and letters. For regex validation, use matches().
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringContainsFullDemo {
public static void main(String[] args) {
String logEntry = "[ERROR] Database connection timed out on port 5432";
// 1. Check severity keyword
if (logEntry.contains("ERROR")) {
System.out.println("Check 1 Passed: Log entry contains 'ERROR'.");
}
// 2. Check empty string behavior (always true)
if (logEntry.contains("")) {
System.out.println("Check 2 Passed: Empty string check returned true.");
}
// 3. Check case sensitivity
if (!logEntry.contains("error")) {
System.out.println("Check 3 Passed: Lowercase 'error' correctly not matched.");
}
System.out.println("All String.contains() unit verification checks passed successfully!");
}
}Terminal Output:
Check 1 Passed: Log entry contains 'ERROR'.
Check 2 Passed: Empty string check returned true.
Check 3 Passed: Lowercase 'error' correctly not matched.
All String.contains() unit verification checks passed successfully!
No. contains() requires a CharSequence. To search for a single character, pass it as a string: str.contains("a") or use str.indexOf('a') != -1.
In Java's standard library, contains(CharSequence s) is implemented as return indexOf(s.toString()) >= 0;.
contains() runs in linear time using simple character loops. matches() compiles a regular expression and matches the entire string, which is significantly slower for simple substring checks.
If the calling string variable is null, calling str.contains(...) throws a NullPointerException.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.