Java String contains() Method

The contain() method checks to see if a character sequence is present in the string. If the characters exist and if they don’t, returns true.

Syntax: public boolean contains(CharSequence chars)

String contains() in Java

  • In Java’s string data type, a variety of methods are available to manage and manipulate the text content.
  • One such method is called the contains(), which allows you to find out if a string has a sequence of characters.
  • For more information, the contains() method is a built-in Java method to check that strings contain any special character or sequence of characters.
  • The syntax for the string contains method is shown here:
string_name.contains($substring);
  • One parameter is allowed in the contains() method: the pattern of characters you want to search for in your string.
  • There are two possible values ​​that can be returned by the contains() function.
  • The contains() method returns true if the substring is in the string you specify; otherwise, it returns false.
  • Suppose that we’re developing a program for the restaurant to check customers’ reservations. The customer’s name and his reservation number should be entered in our programme to check whether their surname matches the last name they specify when making a reservation.

Using this code, we can verify if the customer’s name matches the last name that is stored in a file:

class Techvidvan{
    public static void main(String[] args) {
        String name_on_file = "Tech";
        String name_given_to_clerk = "Vidvan";

        if (name_on_file.contains(name_given_to_clerk)) {
            System.out.println("This reservation is confirmed.");
        } 
else {
            System.out.println("This reservation does not exist.");
        }
    }
}

Signature:

The signature of the string contains() method is given below:

public boolean contains(StringString)

Parameter:

sequence: specifies the sequence of characters to search for.

Exception:

NullPointerException: if sequence is null.

Limitations of the Java Contains() method:

The contains() method shall be limited to the following limitations:

  • To search for a character in a string, the contains() method should not be used.
  • Doing so will result in an error. Only the existence or lack of a string in another string can be checked by contains() method.
  • It’s never going to show the location of the search index. Because of this limitation, it is better to use an indexOf() method instead of the contains().

The Java String contained() method is used for case insensitive check:

We’ve already learned that the contains() method is case sensitive, but with a little trick, you can use this function to perform special insensitivity checks. Let us look at an example and see what’s wrong with it:

In this instance, we will use the toLowerCase method to convert both strings to lowercase while performing a case-insensitive check by means of contains(). To this end, as a result of the example below, we may also use toUpperCase() method.

Example:

classTechvidvan{
  public static void main(String args[]){
String str = "Just a simple STRING";
String str2 = "string";
System.out.println(str.toLowerCase().contains(str2.toLowerCase()));

System.out.println(str.toUpperCase().contains(str2.toUpperCase()));
  }
}

Output:
true
true

Parameters of contains() in Java:

contains() method takes a single parameter. It can be a sequence of characters like string, StringBuffer, etc. Other datatypes like int shall result in an incompatible type error.

Example:

string.contains(“ABC”)

Here, ABC is the sequence of characters taken as the parameter.

Return Values of contains() in Java:

Return Type: boolean

Since contains() is a boolean method. It returns –

  • true: If sequence of characters is present in the string
  • false: If the sequence of characters is not present in the string.

Example:

  • If the given string value does not contain the specified character sequence value, the contains() method returns false.
  • In the following program, we create an object of class string with the value “HelloWorld”. Then we create a sequence of characters with the value “helo”. Using the contains() method, we try to check whether the given string contains the specified sequence of characters or not.
import java.lang.*;
public class Techvidvan{
   public static void main(String[] args) {
            String str1 = new String("HelloWorld");
      System.out.println("Entered string: " + str1);
            CharSequence str2 = "hello";
      System.out.println("The given sequence of characters is: " + str2);
            boolean bool = str1.contains(str2);
      System.out.println("Does the string contain the specified sequence of characters or not?" + bool);
   }
}

Output:
The following is the output of the above program −

Given string: HelloWorld

The given sequence of characters is: hello

Does the string contain the specified sequence of characters or not? False

Overloads:

Contains(Char) Returns a value indicating whether a specified character occurs within this string.
Contains(Char, StringComparison) Returns a value indicating whether a specified character occurs within this string, using the specified comparison

rules.

Contains(String, StringComparison) Returns a value indicating whether a specified string occurs within this string, using the specified comparison rules.

More about the contains() method in Java:

We have seen use cases of contains() method. However, there are some limitations that need to be considered.

  • This method cannot be used for single character searches.
  • This method cannot be used to find the index of the search string in the given string.

The Internal implementation of the method contains():

 public boolean contains(StringString) 
{
 return indexOf(sequence.toString()) > -1; 
}

In this case, the CharSequence is converted to a string, and the indexOf method is called. If the indexOf method finds a string, it will return O or greater otherwise it will return -1. Therefore, if the sequence of character values exists, and that is false or not, contains() method will be True when you execute it.

Points to remember in Java string containing() method:

In order to search for a character, this method does not work. If you don’t have an index of strings, this method doesn’t find it. A better function String indexOf is available in respect of these 2 functions.

Conclusion

contains() method is a built-in Java method that helps us to check whether a sequence of characters is present in a given string or not. The return type of this method is boolean, i.e. it returns true or false. It takes one parameter, i.e. the sequence of characters, to be searched. The main application of this method involves validation tasks, such as checking whether a string is a substring of another.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.