English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java String indexOf() usage and example/String indexOf() method returns the specified character in the string
The index of the first occurrence of the substring.
Syntax of the String indexOf() method
string.indexOf(int ch, int fromIndex)
or
indexOf() parameters
To find the index of a character, indexOf() uses the following two parameters: - ch
The string to find the starting index offromIndex- The character to find the starting index of
If fromIndex is passed, search for the character ch from this index
To find the index of a specified substring in a string, indexOf() uses the following two parameters: - str
The string to find the starting index offromIndex- (Optional)
indexOf() return value/Returns the specified character
The index of the first matching item in the string/If the specified character is not found in the stringReturns -1.
//Java String indexOf() has only one parameter class Main { public static void main(String[] args) { String str1 = "Learn Java"; int result; //Get the index of character 'J' result = str1.indexOf('J'); System.out.println(result); // 6 //Returns the first occurrence of 'a' result = str1.indexOf('a'); System.out.println(result); // 2 //The character is not in the string result = str1.indexOf('j'); System.out.println(result); // -1 //Get the index of 'ava' result = str1.indexOf("ava"); System.out.println(result); // 7 //The substring is not in the string result = str1.indexOf("java"); System.out.println(result); // -1 //Index of an empty string in the string result = str1.indexOf( System.out.println(result); // 0 } }
Note:
The character 'a' appears multiple times in the 'Learn Java' string. The indexOf() method returns the first occurrence of 'a' (i.e.,2)index.
If an empty string is passed, indexOf() returns 0 (found at the first position). This is because an empty string is a subset of every substring.
class Main { public static void main(String[] args) { String str1 = "Learn Java programming"; int result; //Get the index of character 'a' //The search starts from index4start result = str1.indexOf('a', 4); System.out.println(result); // 7 //Get the index of 'Java' //The search starts from index8start result = str1.indexOf("Java", 8); System.out.println(result); // -1 } }
Note:
The first occurrence of 'a' in the 'Learn Java programming' string is at index2at.1Returns the index of the second 'a'. Use indexOf('a', 4). This is because the search starts from index4starts.
The 'Java' string is located in the 'Learn Java programming' string. But, str1.indexOf("Java",8) returned-1(String not found). This is because the search starts from index8Start, and there is no 'Java' in 'va programming'.
Related Reading: Java String lastIndexOf()