The Java String indexOf() method returns the index of a specific character or substring index.

Java String indexOf():

Method signature:

The signatures for an indexOf() method is as shown below.

int indexOf(int character)
int indexOf(int character, int fromIndex)
int indexOf(String substring)
int indexOf(String substring, int fromIndex)

Method parameters and return type:

Return type: It returns an index of a searched substring or a character.

Parameters: This method passes a sequence of characters or a single character with or without an index from where it will start searching.

Throws: It throws NullPointerException if the string is null or the index is less than 0.

Example 1:

You can find an index of a substring in Java using the indexOf() method.

Source code:

public class Example1 {

    public static void main(String args[]) {
        String str = "This is new Java tutorial";
        
        int firstIndex = str.indexOf("Java");
        
        System.out.println(firstIndex);
    }
}

Output:

run:
12
BUILD SUCCESSFUL (total time: 3 seconds)

Example 2:

In this example, we will pass two arguments in the method. The first argument is the substring of which index we need to find and the second argument is the index. After the index passed as a second argument, the method will start searching for the substring.

Source code:

public class Example2 {
    
     public static void main(String args[]) {
        String str = "This is new Java tutorial";
        
        int index = str.indexOf("tutorial", 7); 
        System.out.println(index);
    }
}

Output:

run:
17
BUILD SUCCESSFUL (total time: 1 second)

Example 3:

This method can be used to find index of a specific character.

Source code:

public class Example3 {

    public static void main(String args[]) {
        String str = "This is new Java tutorial";

        int index = str.indexOf('n');
        System.out.println(index); 
    }
}

Output:

run:
8
BUILD SUCCESSFUL (total time: 0 seconds)

References:

Happy Learning 🙂