java.lang.String contains()

Description :

This java tutorial shows how to use the contains() method of java.lang.String class. This method returns a boolean datatype which which is a result in testing if our String contains the characters specified on our method argument in CharSequence object type.

Method Syntax :

public boolean contains(CharSequence s)

Parameter Input :

CharSequence|s|the character sequence to be checked on the String object

Method Returns :

This method returns a boolean datatype which corresponds to the results in checking if our String object contains the CharSequence method parameter.

Compatibility Version :

Requires Java 1.5 and up

Exception :


This exception will be thrown if and only if the parameter CharSequence s is null.

Discussion :

The contains() method of String class is one of my favorite of all the java API. You might be wondering why? The answer is simply that I used it a lot. Come to think of it, how would you check if we want to check if a certain character sequence is in our String object? We could definitely use the matches method of String class which would be very complicated since we will be using regular expression in searching the pattern we desire. Now with contains() method, we are now able to check simple String checking.

Java Code Example :

This example source code demonstrates the use of contains() method of String class. First on our code we have declared our parentString and we have declared our search String in CharSequence object type. We then test if the parentString contains the CharSequence “1234”. If the check is true, we print “The string contains 1234” otherwise “This is a demo” prints on the console.

Sample Output :

Running the contains() method example source code of java.lang.String class will give you the following output

string contains method example

string contains method example

Exception Scenario :

Suggested Reading List :