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. SignatureThe signature of string contains() method is given below: Parametersequence : specifies the sequence of characters to be searched. Returnstrue if the sequence of char value exists, otherwise false. ExceptionNullPointerException : if the sequence is null. Internal implementationHere, 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 ExampleFileName: ContainsExample.java Test it NowOutput: true true false Java String contains() Method Example 2The 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 3The 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 javatpoint.com Java String contains() Method Example 4The 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() methodFollowing are some limitations of the contains() method:
Next TopicJava String endsWith() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India