In Java, the String.contains() method searches the sequence of characters in the given string. It returns a boolean value: true if the string contains the specified sequence of characters, false otherwise.
sequence: Specifies the sequence of characters to be searched.
Returns: true if the sequence of char value exists, otherwise false.
Exception: The method throws NullPointerException if the sequence is null.
This method is particularly useful in a variety of scenarios, such as validating user input, searching keywords in text, filtering data, and more. Its simplicity and readability make it a preferred choice for basic substring checks.
To read more Java String
Here, the conversion of CharSequence takes place into String. After that, the String.indexOf() method is invoked. The method String.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 String.indexOf() method returns -1. Therefore, after execution, the String.contains() method returns true when the String.indexOf() method returns a non-negative value (when the searched string is found); otherwise, the method returns false.
By default, the String.contains() method is case-sensitive. It means that uppercase and lowercase letters are treated differently. For instance:
To perform a case-insensitive search, we can convert both the source string and the search string to the same case using methods like toLowerCase() or toUpperCase():
Output:
true true false
The String.contains() method searches case-sensitive char sequence. If the argument is not case sensitive, it returns false. Let's see an example.
Output:
true true
The String.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.
Output:
This string contains TpointTech.com
The String.contains() method raises the NullPointerException when one passes null in the parameter of the method. The following example shows the same.
Output:
Runtime Error: Exception in thread "main" java.lang.NullPointerException at java.base/java.lang.String.contains(String.java:2058) at Main.main(Main.java:7)
The String.contains() method finds application in various scenarios, including:
We request you to subscribe our newsletter for upcoming updates.