Java String indexOf() Method Tutorial

In this section, we will learn what the String indexOf() method is and how to use it in Java.

What is Java String indexOf() Method?

The Java String indexOf() method is used to search for a character or a sequence of characters in the target string and return its position (index number) if this method found that sequence.

Java indexOf() Method Syntax:

public int indexOf(String str)

public int indexOf(String str, int fromIndex)

public int indexOf(int char)

public int indexOf(int char, int fromIndex)

indexOf() Method Parameters:

As you can see, the method has 4 variants.

  • `str`: this is the character sequence that we want to search for it in the target string and see if it has such string or not.
  • `fromIndex`: inside the target string if we want to start from a specific index, we can add that index as the second argument to the method.

Note: by default, the search begins from the index 0 in the target string.

  • `char`: if we want to look for a character in the target string, we can put that character as the first argument to the method.

indexOf() Method Return Value:

If in the target string there was such character or the string that we set as the argument of the method, the index number of the first occurrence will return. Otherwise, if it wasn’t found, the value -1 will return instead.

Example: using String indexOf() method

public class Simple {

    public static void main(String[] args)  {
        String s1 = "Pure Imagination";
        System.out.println(s1.indexOf('I'));
        System.out.println(s1.indexOf("i",3));
    }
}

Output:

5

9

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies