How to check String contains a substring in Java

In this post, we will see How to check String contains a substring in Java with examples.

There are several ways to check whether a string contains a substring in Java. Let’s see few example.

1. Using the contains() method

The contains() method is a built-in method in Java which returns a boolean value indicating whether a specified substring is present in the original string.

String originalString = "Hello, World!";
String substring = "Hello";

boolean isSubstringPresent = originalString.contains(substring);

if(isSubstringPresent){
   System.out.println("The substring is present in the original string.");
} else {
   System.out.println("The substring is not present in the original string.");
}

Output is – The substring is present in the original string.

2. Using the indexOf() method

The indexOf() method is a built-in method in Java which returns the index of the first occurrence of a specified substring in the original string. If the substring is not found, it returns -1.

String originalString = "Hello, World!";
String substring = "Hello";

int index = originalString.indexOf(substring);

if(index != -1){
   System.out.println("The substring is present in the original string.");
} else {
   System.out.println("The substring is not present in the original string.");
}

Output is – The substring is present in the original string

3. Using regular expressions

Java’s regular expression package (java.util.regex) provides various methods to match patterns in strings. We can use the Matcher class to check if a substring is present in the original string.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String originalString = "Hello, World!";
String substring = "Hello";

Pattern pattern = Pattern.compile(substring);
Matcher matcher = pattern.matcher(originalString);

if(matcher.find()){
   System.out.println("The substring is present in the original string.");
} else {
   System.out.println("The substring is not present in the original string.");
}

Output is – The substring is present in the original string

That’s all about How to check String contains a substring in Java.

See docs