Java String indexOf()
The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Index of the searched string or character.
Java String indexOf() Method Example
FileName: IndexOfExample.javaTest it Now
2 8 5 3
We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example.
In the String: Welcome to JavaTpoint The 'o' character has come 3 times
Java String indexOf(String substring) Method Example
The method takes substring as an argument and returns the index of the first character of the substring.
FileName: IndexOfExample2.javaTest it Now
index of substring 16
Java String indexOf(String substring, int fromIndex) Method Example
The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample3.javaTest it Now
index of substring 16 index of substring -1
Java String indexOf(int char, int fromIndex) Method Example
The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample4.javaTest it Now
index of char 17