Java String contains()
The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false.
Signature
The signature of string contains() method is given below:
Parameter
sequence : specifies the sequence of characters to be searched.
Returns
true if the sequence of char value exists, otherwise false.
Exception
NullPointerException : if the sequence is null.
Internal implementation
Here, the conversion of CharSequence takes place into String. After that, the indexOf() method is invoked. The method indexOf() either returns 0 or a number greater than 0 in case the searched string is found.
However, when the searched string is not found, the indexOf() method returns -1. Therefore, after execution, the contains() method returns true when the indexOf() method returns a non-negative value (when the searched string is found); otherwise, the method returns false.
Java String contains() Method Example
FileName: ContainsExample.java
Output:
true true false
Java String contains() Method Example 2
The contains() method searches case-sensitive char sequence. If the argument is not case sensitive, it returns false. Let’s see an example.
FileName: ContainsExample2.java
Output:
true false
Java String contains() Method Example 3
The contains() method is helpful to find a char-sequence in the string. We can use it in the control structure to produce the search-based result. Let’s see an example.
FileName: ContainsExample3.java
Output:
This string contains tutoraspire.com
Java String contains() Method Example 4
The contains() method raises the NullPointerException when one passes null in the parameter of the method. The following example shows the same.
FileName: ContainsExample4.java
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.lang.String.contains(String.java:2036) at ContainsExample4.main(ContainsExample4.java:9)
Limitations of the Contains() method
Following are some limitations of the contains() method:
- The contains() method should not be used to search for a character in a string. Doing so results in an error.
- The contains() method only checks for the presence or absence of a string in another string. It never reveals at which index the searched index is found. Because of these limitations, it is better to use the indexOf() method instead of the contains() method.