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 :

NullPointerException

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.

package com.javatutorialhq.java.tutorial.string;

/*
 * Java Example Source code to test if String contains a test string
 */

public class StringContainsDemo {

	public static void main(String[] args) {

		// Declaring the parent String object
		String parentString = "1234KatherinAlaska";
		// Declaring the search parameter
		CharSequence searchString = "1234";
		// Test if parentString contains the searchString
		if(parentString.contains(searchString)){
			System.out.println("The string contains "+searchString);
		}
		else{
			System.out.println("This is a demo");
		}
	}

}

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 :

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.contains(Unknown Source)
	at com.teknoscope.java.tutorial.string.StringContainsDemo.main(StringContainsDemo.java:16)

Suggested Reading List :