Check if a String Contains a Substring in Java

In this tutorial, you will learn how to check if a String contains a substring in Java using two built-in methods from the String class:

  1. Using the contains() method
  2. Using the indexOf() method

Check if a String contains a substring using the contains() method

Example

public class Test {

  public static void main(String[] args) {

    String str1 = "Learn Java Programming with alegrucoding.com";
    String str2 = "Learn Java";
    String str3 = "Simple Java Programming";

    // check if str1 contains str2
    if (str1.contains(str2)) {
      System.out.println("str2 is present in str1");
    } else {
      System.out.println("str2 is not present in str1");
    }

    // check if str1 contains str3
    if (str1.contains(str3)) {
      System.out.println("str3 is present in str1");
    } else {
      System.out.println("str3 is not present in str1");
    }

  }
}
Output: str2 is present in str1 str3 is not present in str1
 
Here, we use if-else statements to check if a string contains a specific substring and print a message accordingly. We use specifically the contains() method from the String class to check if strings str2 and str3 are present in str1.

Check if a String contains a substring in Java using the indexOf() method

Example

public class Test {

  public static void main(String[] args) {

    String str1 = "Learn Java Programming with alegrucoding.com";
    String str2 = "Learn Java";
    String str3 = "Simple Java Programming";

    // check if str2 is present in str1
    if (str1.indexOf(str2) > -1) {
      System.out.println("str2 is present in str1");
    } else {
      System.out.println("str2 is not present in str1");
    }

    // check if str3 is present in str1
    if (str1.indexOf(str3) > -1) {
      System.out.println("str3 is present in str1");
    } else {
      System.out.println("str3 is not present in str1");
    }
  }
}
Output: str2 is present in str1 str3 is not present in str1
 
Here, we checked if str2 and str3 are present in str1 using the indexOf() method. If the String is found, its position is returned. Otherwise, -1 is returned.
 
If you’re interested in learning more about manipulating strings in Java, check out our tutorial on how to Get Substring from String in Java.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *