

Her is an example that shows how to use the indexOf() method in Java: String str = "Apple, Orange, & Mango are Fruits." It doesn't make any impact on the performance whichever method you use except that the former is more readable than the latter. Since contains() is implemented using the indexOf() method, they are essentially the same. But it can also be used for substrings matching. Ideally, you should use the indexOf() method to** find the index of a character** in a string. If the string does not contain the given substring, it simply returns -1. Instead, this method returns the index of the first occurrence of the substring. The indexOf() method is different than the contains() method in a way that it doesn't return a boolean value. Another interesting thing to note is that contains() internally calls the indexOf() method (explains below) to check if the given sequence of character exists or not. The contains() method throws a NullPointerException if the given substring is null. Since contains() returns a boolean value, it means that you can use it directly in if statements as shown below: String str = "My name is Atta!" if (str. contains ( "java" ) // falseįor a case-insensitive search, you should convert both string and substring to lowercase as shown below: String str = "My name is Atta!" // case-insensitive search contains ( "There" ) // false "Java 101". It is important to remember that the contains() method is case-sensitive which means it treats uppercase and lowercase characters differently as shown in the below example: "Hey, there!".

Here is an example: String str = "Java is a server-side programming language." The contains() method searches the substring across the original string and returns true if and only if this string contains the specified sequence of character values, and false otherwise. This method returns a boolean value based on whether the substring exists in the this string or not. The first and most popular method used in Java for checking if a string contains another string is contains() from the String class. Let us start with the first commonly used method - contains(). In this article, you'll learn about six different ways of checking if a string contains a substring in Java. You can use contains(), indexOf(), lastIndexOf(), startsWith(), and endsWith() methods to check if one string contains, starts or ends with another string in Java or not. Java provides multiple ways to accomplish this task. One of the most common tasks in Java or any other programming language is to check whether a string contains another string or not.
