All Posts

Java contains() method

Java contains() method

The Java contains() method is used to check whether a string contains a specified sequence of characters. This method is part of the String class and is useful for determining if a particular substring is present within another string.

This method searches the sequence of characters in this string. It returns true if the sequence of char values is found in the string otherwise the method returns false.

contains() method signature

The general method signature is as follows:

public boolean contains(CharSequence sequence)

parameter: sequence

The sequence of characters that you want to search for within the string.

Example

Let’s understand the contains() method using the following example program:

package com.testingdocs.stringmethods;

public class ExampleProgram {

	public static void main(String[] args) {
		String str =" Tic Tac Toe TestingDocs";
		// contains() method demo
		System.out.println("str contains Tic? = " + str.contains("Tic"));
		System.out.println("str contains tac? = " + str.contains("tac"));
		System.out.println("str contains Testing? = " + str.contains("Testing"));
		System.out.println("str contains documents? = "+ str.contains("documents"));
	}
}

Program Output

The program produces the following output as shown below:

str contains Tic? = true

str contains tac? = false

str contains Testing? = true

str contains documents? = false

 

Java contains method

Java Tutorials

Java Tutorial on this website: