The indexOf() method returns the index of the first occurrence of the specified character/substring within the string.
Example
Syntax of indexOf()
The syntax of the String indexOf() method either
string.indexOf(int ch, int fromIndex)
or
string.indexOf(String str, int fromIndex)
Here, string is an object of the String class.
indexOf() Parameters
To find the index of a character, indexOf() takes these two parameters:
- ch - the character whose starting index is to be found
- fromIndex (optional) - if
fromIndexis passed, thechcharacter is searched starting from this index
To find the index of the specified substring within the string, indexOf() takes these two parameters:
- str - the string whose starting index is to be found
- fromIndex (optional) - if
fromIndexis passed, thestrstring is searched starting from this index
indexOf() Return Value
- returns the index of the first occurrence of the specified character/string
- returns -1 if the specified character/string is not found.
Example 1: Java String indexOf()
Notes:
- The character
'a'occurs multiple times in the"Learn Java"string. TheindexOf()method returns the index of the first occurrence of'a'(which is 2). - If the empty string is passed,
indexOf()returns 0 (found at the first position. It is because the empty string is a subset of every substring.
Example 2: indexOf() With fromIndex Parameter
Notes:
- The first occurrence of
'a'in the"Learn Java programming"string is at index 2. However, the index of second'a'is returned whenstr1.indexOf('a', 4)is used. It is because the search starts at index 4. - The
"Java"string is in the"Learn Java programming"string. However,str1.indexOf("Java", 8)returns -1 (string not found). It is because the search starts at index 8 and there is no"Java"in"va programming".
Recommended Reading: Java String lastIndexOf()