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.

Signature

There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:

No.MethodDescription
1int indexOf(int ch)It returns the index position for the given char value
2int indexOf(int ch, int fromIndex)It returns the index position for the given char value and from index
3int indexOf(String substring)It returns the index position for the given substring
4int indexOf(String substring, int fromIndex)It returns the index position for the given substring and from index

Parameters

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.

Returns

Index of the searched string or character.

Internal Implementation

Java String indexOf() Method Example

FileName: IndexOfExample.java

Test it Now

Output:

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.

FileName: IndexOfExample5.java

Output:

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.java

Test it Now

Output:

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.java

Test it Now

Output:

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.java

Test it Now

Output:

index of char 17





Latest Courses