Open In App

Java String contains() method with example

The java.lang.String.contains() method searches the sequence of characters in the given string. It returns true if the sequence of char values is found in this string otherwise returns false. 

Implementation of contains() method

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

Here conversion of CharSequence to a String takes place and then the indexOf method is called. The method indexOf returns O or a higher number if it finds the String, otherwise -1 is returned. So, after execution, contains() method returns true if the sequence of char values exists, otherwise false



Syntax of contains() method

public boolean contains(CharSequence sequence);

Parameter

Exception



Examples of the java.string.contains() method

Example 1: To check whether the charSequence is present or not. 




// Java program to demonstrate working
// contains() method
class Gfg {
 
    // Driver code
    public static void main(String args[])
    {
        String s1 = "My name is GFG";
 
        // prints true
        System.out.println(s1.contains("GFG"));
 
        // prints false
        System.out.println(s1.contains("geeks"));
    }
}

Output
true
false

Example 2: Case-sensitive method to check whether given CharSequence is present or not. 




// Java code to demonstrate case
// sensitivity of contains() method
class Gfg1 {
 
    // Driver code
    public static void main(String args[])
    {
        String s1 = "Welcome! to GFG";
 
        // prints false
        System.out.println(s1.contains("Gfg"));
 
        // prints true
        System.out.println(s1.contains("GFG"));
    }
}

Output
false
true

Points to remember with Java string contains() method


Article Tags :