Java Tutorial Java Advanced Java References

Java String - indexOf() Method



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

Syntax

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

Parameters

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

Return Value

Returns the index number for first occurrence of specified character or string. Returns -1 if there is no such occurrence.

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.

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 string
    System.out.println(MyString.indexOf('J'));

    //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:

0
41

Example:

Here, the indexOf() method is used to find out the index number for first occurrence of specified substring in the given string.

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 "is" in the given string
    System.out.println(MyString.indexOf("is"));

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

The output of the above code will be:

5
46

❮ Java String Methods