java.lang.String indexOf()

Description :

This java tutorial shows how to use the indexOf() method of java.lang.String class. This method returns an int datatype which which corresponds to the index of the string where the method argument str has been found. Note that since we are dealing with String, the index starts at 0.

Method Syntax :

public int indexOf(String str)

public int indexOf(String str, int fromIndex)

Parameter Input :

DataType Parameter Description
String str the string argument which we want to check the position on our String
int fromIndex index on our String where we want to start searching

Method Returns :

This method returns an int datatype which corresponds to the first occurrence index has been found. If the string parameter has not been found on our String, the value returned is -1.

Java Code Example :

This example source code demonstrates the use of indexOf() method of String class. Basically this source code just prints the index of the str method argument on the String object.


 * Java example source code on indexOf method of String class

public class StringIndexOf {

    public static void main(String[] args) {
        System.out.println("java example".indexOf("a"));
        System.out.println("this is a test".indexOf("i", 3));



Sample Output :

Running the indexOf() method example source code of java.lang.String class will give you the following output

java string indexof method example

java string indexof method example

Suggested Reading List :