Java String contains() Method with Example (original) (raw)

Last Updated : 19 Nov, 2024

The**String.contains()** method is used to search for a sequence of characters within a string. In this article, we will learn how to effectively use the string contains functionality in Java.

**Example:

In this example, we check if a specific substring is present in the given string.

Java `

// Java Program to demonstrate working contains() method class Gfg {

public static void main(String args[]) {
  
    String s = "My name is GFG";

    System.out.println(s.contains("GFG"));
    System.out.println(s.contains("geeks"));
}

}

`

Table of Content

**Syntax of contains() method

publicboolean contains(CharSequence _sequence);

**Parameter:

**Return Value:

**Implementation of contains() method

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

Here, the contains() method internally converts the CharSequence to a String and uses the indexOf() method to check for the substring. If indexOf() returns 0 or a positive value, contains() returns true; otherwise, it returns false.

Points to Remember:

Examples of String.contains() Method

Now, we will explore different examples to understand how the contains() method works in Java.

Case-Sensitive Check Using contains() Method

Here, we demonstrate that the contains() method is case-sensitive when searching for substrings.

Java `

// Java Program to demonstrate case sensitivity of contains() method class Gfg1 {

public static void main(String args[])
{
    String s = "Welcome! to GFG";

    System.out.println(s.contains("Gfg"));
    System.out.println(s.contains("GFG"));
}

}

`

Null Handling Using contains() Method

This approach is used to safely handle scenarios, where a null value might be passed to the contains() method, preventing unexpected runtime exceptions.

Java `

// Java program to handle null // using contains() method of String class public class NullHandling {

public static void main(String[] args) {
  
    String s = "Null check";

    try {
        System.out.println(s.contains(null)); // This will throw an exception
    } catch (NullPointerException e) {
        System.out.println("NullPointerException caught: Substring cannot be null.");
    }
}

}

`

Output

NullPointerException caught: Substring cannot be null.

Using StringBuilder

This approach is used when we need to check if a String contains content from a StringBuilder.

Java `

// Java program to check if a String // contains a substring constructed using StringBuilder public class StringBuilderExample {

public static void main(String[] args) {
  
    String s1 = "Welcome to GFG";
    StringBuilder s2 = new StringBuilder("GFG");

    // Check if mainString contains substring
    System.out.println(s1.contains(s2)); // true
}

}

`