Java String contains() method example

HQ » Java Tutorial » java.lang » String » contains() method example
Java String contains() method example 2018-02-19T12:42:09+00:00

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 :

DataType Parameter Description
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 :

Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.