Table of contents
1.
Introduction
2.
String contains() Method in Java
3.
Why Use contains() Over Other String Matching Methods?
4.
Syntax of contains() method
5.
Parameter of contains() method
6.
Exception of contains() method
7.
Returns Value of contains() method
8.
Implementation of contains() method
9.
Example of the java.string.contains() method
9.1.
Example 1: To check whether the charSequence is present or not. 
9.2.
Example 2: Case-sensitive method to check whether given CharSequence is present or not. 
10.
Comparing contains() with Other Methods
10.1.
contains() vs matches()
10.2.
contains() vs equals()
10.3.
contains() vs indexOf()
11.
Limitations of Java string contains() method
12.
Use Cases in Real-World Applications
12.1.
1. Form Validation
12.2.
2. Search Filters in Java Applications
12.3.
3. Keyword Highlighting in Text Editors
13.
Frequently Asked Questions
13.1.
How do I check if a string contains a specific sequence of characters?
13.2.
How do you compare strings in Java?
13.3.
How do I find a word in a string in Java?
13.4.
What does string () do in Java?
14.
Conclusion
Last Updated: Jul 7, 2025
Easy

Java String contains() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, strings are objects representing a sequence of character values. An array of characters work the same as a string in Java. The Java String class has a lot of methods to perform operations on strings like compare(), concat(), equals(), split(), length(), replace(), compareTo(), contains(). The string contains() method is used when you need to check whether a string contains a certain sequence of characters or not. In this article, we will learn about the string contains() method with the help of code examples. Let us dive into the topic.

java string contains method

String contains() Method in Java

The String.contains() method is used to search a sequence of characters in the given string. If the sequence of char values is found in this string, it returns true, otherwise returns false. 

Why Use contains() Over Other String Matching Methods?

In real-world Java applications, the Java String contains() method is often preferred for its simplicity and readability when checking for the presence of a substring. It returns a boolean and is especially useful in conditional statements.

Let’s compare it with other Java string matching methods:

  • contains() – Checks if a substring exists within a string.
    → Ideal for readability and quick substring checks: if (str.contains("admin")).
  • equals() – Compares two strings for exact match.
    → Too strict for partial matches; use only when full equality is needed.
  • matches() – Uses regular expressions to match patterns.
    → Powerful but less readable and overkill for simple substring searches.
  • indexOf() – Returns the position of a substring or -1 if not found.
    → Functional but less expressive than contains() for conditional checks.
  • Why use contains()?
    → Simpler syntax, easier to read, and best suited for common real-world use cases like filtering, validation, or log scanning.

Syntax of contains() method

public boolean contains(CharSequence sequence)    

Parameter of contains() method

sequence: It specifies the sequence of characters to be searched.

Exception of contains() method

NullPointerException: If the sequence is null

Returns Value of contains() method

true if the sequence of char values exist; otherwise, false.

Implementation of contains() method

public boolean contains(CharSequence sequence)
{
   return indexOf(sequence.toString()) > -1;
}

In this case, CharSequence is converted to a String and then indexOf is called. If indexOf finds the String, it returns O or a higher number, otherwise -1. In other words, if a sequence of char values exists, the contains() method returns true, otherwise it returns false. 

Example of the java.string.contains() method

Let us look over a few examples to understand the concepts better.

Example 1: To check whether the charSequence is present or not. 

class Ninja1 {
    public static void main(String args[]) {
        String var1 = "My company's name is CodingNinjas";
        
        // Checking if "CodingNinjas" is present in var1
        System.out.println(var1.contains("CodingNinjas")); // This will print true
        
        // Declare and initialize a new string for another check
        String s1 = "CN";
        System.out.println(var1.contains(s1)); // This will print false since "CN" is not a part of var1
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output: 

true
false

Example 2: Case-sensitive method to check whether given CharSequence is present or not. 

class Ninja2 {
    public static void main(String args[]) {
        String var2 = "CodingNinjas";
        
        // Checking if 'var2' contains "Ninjas"
        System.out.println(var2.contains("Ninjas")); // This will print true
        
        // Checking if 'var2' contains "NINJAS" (case-sensitive check)
        System.out.println(var2.contains("NINJAS")); // This will print false
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output: 

true
false

Comparing contains() with Other Methods

contains() vs matches()

  • contains() checks if a substring exists in the given string, while matches() uses regular expressions to match the entire string.
  • contains() is simpler and more readable for basic substring checks, whereas matches() is suited for pattern validation.
  • Example:
String input = "welcome123";
input.contains("123");    // true
input.matches(".*123.*"); // true – but uses regex
  • Use contains() for readability and performance in most substring checks. Use matches() when regex is truly needed.

contains() vs equals()

  • equals() checks if two strings are exactly the same (case-sensitive), while contains() checks for a substring within a string.
  • contains() is more flexible and useful for partial matching or filtering scenarios.
  • Example:
String name = "Narayan Mishra";
name.equals("Narayan");      // false
name.contains("Narayan");    // true
  • Use equals() for full string identity; use contains() for partial match conditions in real-world use cases like search filters.

contains() vs indexOf()

  • Both methods can check for the presence of a substring, but contains() is more expressive.
  • indexOf() returns the index of the substring (or -1 if not found), while contains() returns a boolean.
  • Example:
String data = "user_admin_role";
data.indexOf("admin") != -1;   // true
data.contains("admin");        // true – cleaner and more readable
  • Use contains() when you simply need to check presence; use indexOf() when you need the position too.

Limitations of Java string contains() method

  • Case Sensitivity: The method is case-sensitive, making it unable to perform case-insensitive searches directly.
  • No Regular Expression Support: contains() only checks for literal substrings and does not support regex.
  • Performance with Large Strings: It can be inefficient with large strings, especially when used frequently, due to its linear time complexity.
  • Null Handling: Passing a null argument to contains() will result in a NullPointerException, requiring manual null checks.
  • No Index Information: It only returns a boolean, without indicating the position of the substring in the string.
  • Immutable Strings: Since Java strings are immutable, contains() cannot modify the string; it only checks for the substring's presence.

Use Cases in Real-World Applications

1. Form Validation

In form validation, String.contains() is commonly used to detect forbidden or required substrings in user input. For instance, it can help ensure that an email address includes essential elements like "@" or prevent insecure keywords like "script".

String email = "testuser@example.com";
if (!email.contains("@")) {
    System.out.println("Invalid email address.");
}

This approach simplifies validation checks without the need for full regex parsing, making it ideal for lightweight input screening.

2. Search Filters in Java Applications

In search functionality, contains() is widely used to filter lists based on partial input. This helps in creating dynamic, real-time filtering systems, such as filtering product names or user records.

List<String> products = List.of("Laptop", "Desktop", "Tablet", "Monitor");
String query = "top";
products.stream()
        .filter(p -> p.toLowerCase().contains(query.toLowerCase()))
        .forEach(System.out::println); // Prints "Laptop", "Desktop" 

It enhances user experience with quick and intuitive substring filtering.

3. Keyword Highlighting in Text Editors

Text editors or content analysis tools often use contains() to detect and highlight keywords or flagged words in a document. This enables simple yet effective string scanning.

String document = "Please avoid using the word 'confidential'.";
if (document.contains("confidential")) {
    System.out.println("Highlight the word: confidential");
}

This is especially useful in comment moderation tools, IDEs, or educational software.

Frequently Asked Questions

How do I check if a string contains a specific sequence of characters?

The String.contains() method is used to search the sequence of characters in the given string. If the sequence of char values is found in this string, it returns true, otherwise returns false. 

How do you compare strings in Java?

The equals() method is used to compare two strings in java.

How do I find a word in a string in Java?

To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string.

What does string () do in Java?

In Java, String() is a constructor that creates a new String object. It can initialize a string from various sources, such as character arrays, byte arrays, or another string. While strings are usually created using literals, the String() constructor allows for more flexible and explicit string creation.

Conclusion

The Java String contains() Method is a straightforward and effective tool for checking the presence of a substring within a string. While it is case-sensitive and lacks regex support, it serves well for simple substring checks. However, for complex searches or large datasets, consider its limitations and explore alternative methods to optimize performance and functionality in your Java applications.

Also read:

Live masterclass