Java String contains() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The contains() method answers a simple question: “Does this string include that substring?” It returns true or false, which makes it perfect for validation, filtering, and readable if statements.

01

Substring Search

Find text anywhere.

02

Returns boolean

true or false.

03

CharSequence

String parameter type.

04

Case Sensitive

A ≠ a by default.

05

vs indexOf()

Presence vs position.

06

Validation

Keywords and input.

Definition and Usage

In Java, contains(CharSequence sequence) is defined on java.lang.String. It searches the entire string for the first occurrence of the argument as a contiguous block of characters. If "Hello, Java Programming!" contains "Java", the method returns true.

Unlike startsWith() or endsWith(), contains() matches the substring anywhere in the text—beginning, middle, or end.

💡
Beginner Tip

When you only need yes/no, prefer contains() over indexOf(...) >= 0. It communicates intent clearly: “Is this text present?”

📝 Syntax

The contains() method is declared in the String class:

java
public boolean contains(CharSequence sequence)

Parameters

  • sequence — the substring to search for. Must not be null.

Return Value

Returns true if sequence appears as a substring; otherwise false.

Exceptions

Throws NullPointerException if sequence is null.

⚡ Quick Reference

ExpressionResult
"Hello, Java!".contains("Java")true
"Hello, Java!".contains("Python")false
"Hello".contains("hello")false (case-sensitive)
"Hello".contains("")true (empty sequence)
"abc".indexOf("b") >= 0Same idea as contains("b")
Basic check
text.contains("Java")

Keyword present?

Negate
!email.contains("@")

Invalid input

Ignore case
s.toLowerCase().contains("java")

Normalize first

Need index?
text.indexOf("Java")

Use indexOf instead

Examples Gallery

These programs run in Java 8+. They show a basic match, a failed search, case rules, case-insensitive validation, and comparison with indexOf().

📚 Getting Started

Check whether a programming greeting includes the word Java.

Example 1 — Basic Substring Check

Search "Hello, Java Programming!" for the substring "Java".

java
public class StringContainsExample {
    public static void main(String[] args) {
        String text = "Hello, Java Programming!";

        boolean containsJava = text.contains("Java");

        System.out.println("Contains 'Java'? " + containsJava);
    }
}

How It Works

Java scans the string and finds J-a-v-a in the middle of the sentence. Because the substring appears contiguously, contains returns true.

Example 2 — Substring Not Present

When the search text is absent, contains() returns false without throwing an exception.

java
public class NotFoundDemo {
    public static void main(String[] args) {
        String course = "Java Programming";

        System.out.println("Contains Python? " + course.contains("Python"));
        System.out.println("Contains Prog?   " + course.contains("Prog"));
    }
}

How It Works

Python does not appear anywhere, so the result is false. Prog is a valid partial match inside Programmingcontains() does not require whole-word matches unless you add that logic yourself.

📈 Practical Patterns

Case rules, validation, and choosing the right search method.

Example 3 — Case-Sensitive Matching

Letter case matters. java lowercase is not the same as Java.

java
public class CaseSensitive {
    public static void main(String[] args) {
        String title = "Learn Java Today";

        System.out.println("Contains 'Java'? " + title.contains("Java"));
        System.out.println("Contains 'java'? " + title.contains("java"));
    }
}

How It Works

The capital J in the string matches the search for "Java" but not "java". Always account for case when validating user input.

Example 4 — Case-Insensitive Keyword Check

Normalize both sides to lowercase before calling contains() when case should not matter.

java
public class IgnoreCaseSearch {
    public static boolean containsIgnoreCase(String text, String keyword) {
        return text.toLowerCase().contains(keyword.toLowerCase());
    }

    public static void main(String[] args) {
        String input = "I love JAVA programming";

        System.out.println(containsIgnoreCase(input, "java"));
    }
}

How It Works

Both strings become lowercase before comparison, so JAVA in the input matches the keyword java. For locale-sensitive text, consider toLowerCase(Locale) instead of the default locale.

Example 5 — contains() vs indexOf()

Use contains() for presence; use indexOf() when you need the position.

java
public class ContainsVsIndexOf {
    public static void main(String[] args) {
        String url = "https://codetofun.com/java";

        boolean hasJava   = url.contains("/java");
        int javaPosition  = url.indexOf("/java");

        System.out.println("contains:  " + hasJava);
        System.out.println("indexOf:   " + javaPosition);
    }
}

How It Works

Both detect the substring, but indexOf also tells you it starts at index 23—useful for slicing with substring() afterward.

🚀 Common Use Cases

  • Input validation — reject emails without @ or passwords missing required symbols.
  • Keyword filtering — flag messages that include banned or required words.
  • URL and path checks — test whether a link includes https:// or a route segment.
  • Simple search — highlight rows in a list when the user’s query appears in the text.
  • Feature toggles in text — branch logic when configuration strings include a token.

🧠 How contains() Works

1

You pass a sequence

Java receives the host string and the substring to locate.

Input
2

Null is rejected

A null argument throws NullPointerException immediately.

Validate
3

Substring scan

The JVM searches for the sequence using an optimized index scan (similar to indexOf internally).

Search
=

boolean answer

true if found anywhere; false if not.

📝 Notes

  • contains() is case-sensitive unless you normalize case first.
  • It matches substrings anywhere—not necessarily whole words.
  • contains("") always returns true for any string.
  • The parameter type is CharSequence, so StringBuilder values work too.
  • For “starts with” or “ends with” checks, use startsWith() or endsWith() instead.

⚡ Optimization

contains() is optimized for general substring search and is the right default for most applications. If you call the same check repeatedly in a hot loop, store the boolean result in a local variable. For very large texts and advanced pattern matching, regular expressions or specialized libraries may be appropriate—but start with contains() for simple literal searches.

Conclusion

The contains() method is one of the most readable ways to test substring presence in Java. Its boolean return type fits naturally inside conditionals for validation and filtering.

Remember case sensitivity, the empty-string edge case, and when to reach for indexOf() instead. With those details in mind, you can write clear search logic without extra boilerplate.

💡 Best Practices

✅ Do

  • Use contains() for readable presence checks
  • Normalize case when users may type in any capitalization
  • Guard against null arguments before calling
  • Combine with startsWith() / endsWith() when position matters
  • Cache the result if you reuse the same check many times

❌ Don’t

  • Assume contains() ignores case by default
  • Pass null as the search sequence
  • Use indexOf >= 0 when contains() reads clearer
  • Expect whole-word matching without extra logic
  • Confuse substring presence with full string equality (equals())

Key Takeaways

Knowledge Unlocked

Five things to remember about contains()

Use these points whenever you search inside a Java string.

5
Core concepts
02

Returns boolean

true or false.

Return
🔑 03

Case Sensitive

Normalize if needed.

Edge case
📈 04

Validation

Keywords, emails.

Use case
🔢 05

vs indexOf()

Presence vs index.

Compare

❓ Frequently Asked Questions

contains(CharSequence sequence) checks whether the calling string includes the given character sequence anywhere as a contiguous substring. It returns true if found and false otherwise.
Call it on any String: text.contains("Java"). The parameter type is CharSequence, so String and StringBuilder arguments work. It returns a boolean.
Yes. "Hello".contains("hello") returns false because uppercase and lowercase letters are different. For case-insensitive checks, normalize both sides with toLowerCase() or use a case-insensitive approach before calling contains().
contains() returns true/false and reads naturally in if conditions. indexOf() returns the starting index (0 or greater) or -1 when missing. Use contains() for presence checks; use indexOf() when you also need the position.
Every string contains the empty sequence, so contains("") always returns true. This is defined by the Java API and rarely matters in everyday code, but it is good to know for edge-case tests.
Use it to validate user input, filter keywords, guard business rules ("does this URL include https?"), or simplify search logic whenever you only need a yes/no answer about substring presence.

Search and Build Strings with Confidence

Next up: compare full character sequences with contentEquals() when working with StringBuilder.

Next: contentEquals() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful