Java Program to search a word inside a string

In this code example we are going to learn how to find a specific word or text inside a string. For this example we will utilize the java.lang.String class. The String class provides a method called String.indexOf(). It takes an argument of a String, which is the substring that we want to find in the other string. You can imagine the substring as a needle that we are going to find in the haystack.

If the word found more than once in the string, the indexOf() method returns the first index of a substring found in the specified string. If the substring can’t be found this method return-1 The index of string returns by this method begins at zero. It means that the first letter in the string has the index number 0.