Java String contains()

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

Example

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

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

Syntax of contains()

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 character
  • returns false if the string doesn't contain the specified character

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 "java" 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

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges