Java String indexOf() Syntax

The syntax of Java String indexOf() Method is:

Java indexOf() Parameters

Below are the indexOf() Java String parameters: char – Used to represent a single character value str – Used to represent the string to search for fromIndex – Used to represent the index position to start the search from

Java String indexOf() Return Value

This indexOf() Java String method returns the index within this string of the first occurrence of the specified character. It returns -1 if the character does not occur. The Java String IndexOf method has four overloads. All the overloads return an integer type value, representing the returned index. These overloads differ in the type and number of parameters they accept.

IndexOf(char b)

This method returns the index of the character ‘b’ passed as parameter. If that character is not available in the string, the returned index would be -1.

IndexOf(char c, int startindex)

The given method would return the index of the first occurrence of character ‘c’ after the integer index passed as second parameter “startindex.” All the occurrences of character ‘c’ before the “startindex” integer index would be ignored.

IndexOf(String substring)

The above Java substring indexOf() method returns the index of the first character of the substring passed as a parameter to it. If that substring is not available in the string, the returned index would be -1.

IndexOf(String substring, int startindex)

This Java substring indexOf() method returns the index of the first character in the substring passed as the first parameter, after the “startindex” index value. If substring starts from the passed integer value of “startindex”, that substring would be ignored.

Java String indexOf() Method example

Output:

Index of character ‘x’: 12 Index of character ‘s’ after 3 index: 3 Index of substring ‘is’: 2 Index of substring ‘is’ form index:5