Join our newsletter for the latest updates.

Java Program to Check if a string contains a substring

In this example, we will learn to check if a string contains a substring using contains() and indexOf() method in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Check if a string contains a substring using contains()

class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Programiz";
    String str1 = "Programiz";
    String str2 = "Programming";

    // check if name is present in txt
    // using contains()
    boolean result = txt.contains(str1);
    if(result) {
      System.out.println(str1 + " is present in the string.");
    }
    else {
      System.out.println(str1 + " is not present in the string.");
    }

    result = txt.contains(str2);
    if(result) {
      System.out.println(str2 + " is present in the string.");
    }
    else {
      System.out.println(str2 + " is not present in the string.");
    }
  }
}

Output

Programiz is present in the string.
Programming is not present in the string.

In the above example, we have three string txt, str1, and str2. Here, we have used the String contains() method to check if strings str1 and str2 are present in txt.


Example 2: Check if a string contains a substring using indexOf()

class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Programiz";
    String str1 = "Programiz";
    String str2 = "Programming";

    // check if str1 is present in txt
    // using indexOf()
    int result = txt.indexOf(str1);
    if(result == -1) {
      System.out.println(str1 + " not is present in the string.");
    }
    else {
      System.out.println(str1 + " is present in the string.");
    }

    // check if str2 is present in txt
    // using indexOf()
    result = txt.indexOf(str2);
    if(result == -1) {
      System.out.println(str2 + " is not present in the string.");
    }
    else {
      System.out.println(str2 + " is present in the string.");
    }
  }
}

Output

Programiz is present in the string.
Programming is not present in the string.

In this example, we have used the String indexOf() method to find the position of the strings str1 and str2 in txt. If the string is found the position of the string is returned. Otherwise, -1 is returned.