VOOZH about

URL: https://www.geeksforgeeks.org/java/java-string-contains-method-example/

⇱ Java String contains() Method with Example - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java String contains() Method with Example

Last Updated : 11 Jul, 2025

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.


Output
true
false

Syntax of contains() method

public boolean contains(CharSequence sequence);

Parameter:

  • sequence: This is the sequence of characters to be searched.

Return Value:

  • Returns true, if the sequence is found.
  • Returns false, if not found.

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:

  • Case-Sensitive: The contains() method is case-sensitive, so "Java" and "java" are treated differently. because, first "J" is in upper case and the second "j" is in lower case.
  • Null Handling: Passing null as a parameter will throw a NullPointerException.
  • Supports CharSequence: It works with String, StringBuilder, and StringBuffer.

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.


Output
false
true


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.


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.


Output
true


Comment