Java – String contains(CharSequence s) method with example

In this article, we will discuss to check whether particular character sequence exists or not in the invoking string content/value

1. String’s contains(CharSequence str):

  • This String method examines whether particular character sequence present in the invoking string content/value or NOT
  • And respectively returns a boolean-value either true or false

1.1 Method Signature:

public boolean contains(CharSequence s);

1.2 Returns:

Returns a boolean value either true or false

  • True –> if character sequence exists in the invoking-string
  • False –> if character sequence is not exists in the invoking-string

1.3 Throws:

  • String’s contains() method throws NullPointerException, if character sequence supplied/passed is NULL

2. Examples on String.contains() method:

2.1 Checking whether character sequence exists or NOT

StringContainsMethod.java

package in.bench.resources.string.methods;

public class StringContainsMethod {

	public static void main(String[] args) {

		String str1 = "Welcome to BenchResources.Net weblog";

		// search 1: searching char-value present
		boolean search1 = str1.contains("BenchRes");

		// printing to console
		System.out.println(search1);

		// search 2: searching char-value not exists
		boolean search2 = str1.contains("tech weblog");

		// printing to console
		System.out.println(search2);
	}
}

Output:

true
false

2.2 Exception scenario by passing NULL value

StringContainsMethod.java

package in.bench.resources.string.methods;

public class StringContainsMethod {

	public static void main(String[] args) {

		String str1 = "Welcome to BenchResources.Net weblog";

		// search 1: searching NULL value
		boolean search1 = str1.contains(null);

		// printing to console
		System.out.println(search1);
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.contains(String.java:2076)
	at in.bench.resources.string.methods.StringContainsMethod
                               .main(StringContainsMethod.java:10)

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String contentEquals(StringBuffer sb) method
Java - String concat(String str) method