![]() |
VOOZH | about |
The String.contains() method is used to search for a sequence of characters within a string. In this article, we will learn how to effectively use the string contains functionality in Java.
Example:
In this example, we check if a specific substring is present in the given string.
true false
Table of Content
public boolean contains(CharSequence sequence);
Parameter:
Return Value:
Returns true, if the sequence is found.Returns false, if not found.public boolean contains(CharSequence sequence)
{
return indexOf(sequence.toString()) > -1;
}Here, the contains() method internally converts the CharSequence to a String and uses the indexOf() method to check for the substring. If indexOf() returns 0 or a positive value, contains() returns true; otherwise, it returns false.
contains() method is case-sensitive, so "Java" and "java" are treated differently. because, first "J" is in upper case and the second "j" is in lower case.null as a parameter will throw a NullPointerException.CharSequence: It works with String, StringBuilder, and StringBuffer.String.contains() MethodNow, we will explore different examples to understand how the contains() method works in Java.
contains() MethodHere, we demonstrate that the contains() method is case-sensitive when searching for substrings.
false true
This approach is used to safely handle scenarios, where a null value might be passed to the contains() method, preventing unexpected runtime exceptions.
NullPointerException caught: Substring cannot be null.
This approach is used when we need to check if a String contains content from a StringBuilder.
true