Join our newsletter for the latest updates.

Java String contains()

The String contains() method checks whether the specified string (sequence of characters) is present in the string or not.

The syntax of the String contains() method is:

string.contains(CharSequence ch)

Here, string is an object of the String class.


contains() Parameters

The contains() method takes a single parameter.

  • ch (charSequence) - a sequence of characters

Note: A charSequence is a sequence of characters such as: String, CharBuffer, StringBuffer etc.


contains() Return Value

  • returns true if the string contains the specified ch
  • returns false if the string doesn't contain the specified ch

Example 1: Java String contains()

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    Boolean result;

    // check if str1 contains "Java"
    result = str1.contains("Java");
    System.out.println(result); // true

    // check if str1 contains "Python"
    result = str1.contains("Python");
    System.out.println(result); // false

    // check if str1 contains ""
    result = str1.contains("");
    System.out.println(result); // true
  }
}

Here, str.contains("") gives true because the empty string is a subset of every other string.


Example 2: Using contains() With if...else

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    String str2 = "Java";
    String str3 = "java";
    Boolean result;
    
    // true because "Learn Java" contains "Java"
    if (str1.contains(str2)) {
      System.out.println(str1 + " contains " + str2);
    }
    else {
      System.out.println(str1 + " doesn't contains " + str2);
    }
    
    // contains() is case-sensitive
    // false because "Learn Java" doesn't contains "ava"
    if (str1.contains(str3)) {
      System.out.println(str1 + " contains " + str3);
    }
    else {
      System.out.println(str1 + " doesn't contain " + str3);
    }
  }
}

Output

Learn Java contains Java
Learn Java doesn't contain java