Java String contains() Method

      No Comments on Java String contains() Method




Java String contains() method is used to check whether a string contains the specified sequence of char values in case-sensitive way.
i.e.
String str = “This is masterjavatutorial.com website”;
System.out.println(str.contains(“com”)); // This will be true

String str = “This is masterjavatutorial.com website”;
System.out.println(str.contains(“Com”)); // This will be false as it is case-sensitive search. “Com” here begins with capital “C”.

Signature of contains() method:

 boolean contains(CharSequence s)

CharSequence is the super class of String class. So, String can be passed as an argument while checking.
e.g.

String str = “This is masterjavatutorial.com website”;
System.out.println(str.contains(“com”));

This method return type is boolean. It returns true when a string contains the specified sequence of char values.

Internal Implementation of contains() method:

Internally, this method uses indexOf() method of String class only. The internal implementation of contains method in String is as below:

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

Let’s take few examples of contains() method.

Example 1: Java String contains() method

package com.masterjavatutorial;
public class Test {
    public static void main(String[] args) {
	String str ="This is masterjavatutorial.com website";
        System.out.println(str.contains("com"));   		
    }
}

The output of the method is as below:

true

Example 2: Java String contains() method

package com.masterjavatutorial;
public class Test {
    public static void main(String[] args) {
	String str ="This is masterjavatutorial.com website";
        System.out.println(str.contains("Com"));   //Case-sensitive Search		
    }
}

The output of the method is as below:

false






Leave a Reply