Java Program to Check if a string contains a substring

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()

Output

nodmek 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()

Output

nodmek 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.