Java: String contains(CharSequence s) method

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

 

contains(CharSequence s):

  • 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

Method Signature:

public boolean contains(CharSequence s);

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

Throws:

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

 

Examples on contains() method:

Example 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

 

Example 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)

 

References:

 

Happy Coding !!
Happy Learning !!

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