String method- indexof

indexof method is used to find out the index of a particular character or Substring into the String.

It has 4 type of different signatures.

  1. int indexOf(int ch)
  2. int indexOf(String str)
  3. int indexOf(int ch,int fromIndex)
  4. int indexOf(String str, int fromIndex)

We should know that index starts from number 0. Let’s see their implementation with examples.

int indexOf(int ch):

It returns the index of the first occurrence of character ch in a String.

Output: index of char ‘e’ : 1


int indexOf(String str):

Returns the index of a substring in a String. We are searching the index of substring ‘World’ in a string ‘Hello World’.

Output: index of char ‘World’ : 6


int indexOf(int ch,int fromIndex):

It returns the index of first occurrence of character ch, starting from the specified index “fromIndex”. In the below example, we are finding the character ‘W’ in the String.

Output: index of char ‘W’ ,start from 4th position : 6


int indexOf(String str, int fromIndex):

Returns the index of string str, starting from the specified index “fromIndex”.

Output: index of String ‘Hello’ ,start from 2nd position : 4
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
String methods - equals() and equalsIgnoreCase()
String methods - trim() and length()
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 6, 2015

    […] indexOf(String str, int fromIndex) […]