Java String indexOf() Method Example

There are 4 types of an indexOf method in java. The signature of indexOf methods are given below:
  • indexOf(int ch)  - Returns the index within this string of the first occurrence of the specified character.
  • indexOf(int ch, int fromIndex)  - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
  • indexOf(String str) -  Returns the index within this string of the first occurrence of the specified substring.
  • indexOf(String str, int fromIndex) -  Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Java String indexOf() Method Example

This program demonstrates the example of all the 4  indexOf()  methods.
public class IndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
         // method 1
        int index = str.indexOf("java");
        System.out.println(index);
         // Remember index starts with 0 so count from 0
        System.out.println("index of guides :: " + str.indexOf("guides"));
        System.out.println(" index of des :: " + str.indexOf("des"));
         // method 2
        System.out.println(str.indexOf('s'));
         // method 3
        System.out.println(str.indexOf('g', 0));
         // method 4
        System.out.println(str.indexOf("guides", 3));
    }
}

Output:
0 index of guides:: 4 index of des:: 7 9 4 4 

Reference


Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course