Java String indexOf example

String’s indexOf method is used to find out index of any character or sub string.

indexOf method can take char or string as argument and also you can provide fromIndex(Index after which you want to use indexOf method) also.

Methods:

public int indexOf(int ch)
returns index of first occurrence of character within String

public int indexOf(int ch,int fromIndex)
returns index of first occurrence of character within String, starting from specific index “fromIndex”

public int indexOf(String)
returns index of first occurrence of substring within String

public int indexOf(int ch,int fromIndex)
returns index of first occurrence of substring within String, starting from specific index “fromIndex”

All indexOf methods return -1 if char or substring is not present in the String

String indexOf Example:

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *