String indexOf(String str int fromIndex) method in java

Let’s learn String indexOf(String str, int fromIndex) method in java.

String indexOf(String str, int fromIndex) method in java

String indexOf(String str, int fromIndex) method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Syntax:

public int indexOf(String str, int fromIndex)

Parameters:

str the substring to search for.

fromIndex the index from which to start the search.

Now let’s see example on String indexOf(String str, int fromIndex) method.

public class StringIndexOfMethodExample
{
   public static void main(String[] args)
   {
      String strInput = new String("hello world core java");
      String strSub = new String("core");
      System.out.print("Index found: " );
      System.out.println(strInput.indexOf(strSub, 3));
   }
}

Output:

Index found: 12


Now let’s see another example where substring is present in sequence but search index is greater than index of substring.

public class StringIndexOfMethodExample
{
   public static void main(String[] args)
   {
      String strInput = new String("hello world core java");
      String strSub = new String("core");
      System.out.print("Index found: " );
      System.out.println(strInput.indexOf(strSub, 16));
   }
}

Output:

Index found: -1


Also read – major features of java