Java.lang Package Classes

Java String - indexOf() Method



The java.lang.String.indexOf() method is used to find out the index number for first occurrence of specified character in the specified substring of the given string starting at the specified index.

Syntax

public int indexOf(int ch, int fromIndex)

Parameters

ch specify the character to search for.
fromIndex specify the index from which to start the search.

Return Value

Returns the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

Exception

NA.

Example:

In the example below, indexOf() method is used to find out the index number for first occurrence of specified character in the given string.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Java is a programming language. Learning Java is fun.";

    //index number of first occurrence 
    //of 'J' in the given substring
    System.out.println(MyString.indexOf('J', 20));   
  }
}

The output of the above code will be:

41

❮ Java.lang - String