In this tutorial, you will learn about String contains() method, its syntax, and usage with examples.

Java String contains() method

In Java, String contains() method takes a string value as argument, and checks if the given argument string is present in the string.

Syntax of contains()

The syntax to call String contains() method in Java is

string1.contains(string2)

contains() has a single parameter.

ParameterDescription
string2[Mandatory]A CharSequence value.This value is search in string1. If found returns true, else returns false.

contains() returns value of boolean type.

ADVERTISEMENT

Examples

1. contains() – The string contains given argument string

In this example, we take two strings: string1 and string2; and check if the string string1 contains the string string2 using String contains() method. We have taken the string values such that string1 contains string2.

Java Program

public class Main {
	public static void main(String[] args) {
		String string1 = "Apple is red in color.";
		String string2 = "red";
		
		if (string1.contains(string2)) {
			System.out.println("string1 CONTAINS string2.");
		} else {
			System.out.println("string1 DOES NOT CONTAIN string2.");
		}
	}
}

Output

string1 CONTAINS string2.

Since string1 contains string2, the contains() method returns true, and the if-block is run.

2. contains() – The string does not contain given argument string

In this example, we take take the string values such that the string string1 does not contain the string string2 and check the result of String contains() method.

Java Program

public class Main {
	public static void main(String[] args) {
		String string1 = "Apple is red in color.";
		String string2 = "blue";
		
		if (string1.contains(string2)) {
			System.out.println("string1 CONTAINS string2.");
		} else {
			System.out.println("string1 DOES NOT CONTAIN string2.");
		}
	}
}

Output

string1 DOES NOT CONTAIN string2.

Since string1 does not contain string2, the contains() method returns false, and the else-block is run.

Conclusion

In this Java String Methods tutorial, we have seen about String contains() method in Java, its syntax, and how to use String contains() method in Java programs with the help of examples.