Java String contains(): Substring Presence & Sequence Verification

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().

1. Syntax & Method Signature 🔝

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.

2. Basic Substring Checking 🔝

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"));        // false

Terminal Output:

true
true
true
true
false

3. CharSequence Polymorphism: Strings, StringBuilders, and Buffers 🔝

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));     // true

Terminal Output:

true
true
true

4. contains() vs. indexOf(): High-Contrast Comparison 🔝

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

5. Case-Insensitive Substring Checking 🔝

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);                 // true

Terminal Output:

Direct check:          false
Normalized lowercase:  true

6. Null-Safety & Exception Prevention 🔝

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);  // false

Terminal Output:

Caught NullPointerException on null needle!
Safe check result: false

7. Production Recipe: Content Moderation & Word Blacklist Filter 🔝

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

8. Common Developer Pitfalls & Traps 🔝

The Empty String Always Returns True

Calling str.contains("") always evaluates to true for any non-null string, because every string conceptually contains the empty sequence.

contains() Does Not Support Regular Expressions

contains() searches for exact literal characters. Passing regex patterns like str.contains("\d+") searches for literal backslashes and letters. For regex validation, use matches().

9. Complete Compilable Java Program 🔝

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!

10. Frequently Asked Questions (FAQ) 🔝

Can contains() search for a single char primitive?

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.

How does contains() work under the hood?

In Java's standard library, contains(CharSequence s) is implemented as return indexOf(s.toString()) >= 0;.

What is the performance difference between contains() and matches()?

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.

What happens when calling contains() on null?

If the calling string variable is null, calling str.contains(...) throws a NullPointerException.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer