Search a word inside a string in Java

This example shows you on how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.

public class StringSearch{
   public static void main(String[] args) {
      String strOrig = "Hello Java";
      int intIndex = strOrig.indexOf("Java");
      if(intIndex == - 1){
         System.out.println("Java not found");
      }else{
         System.out.println("Found Java at index " + intIndex);
      }
   }
}
Result:
The above code sample will produce the following result.
Found Java at index 6


Source code: