All for Joomla All for Webmasters

Java String indexOf

The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.


Signature

There are 4 types of indexOf method in java. The signature of indexOf methods are given below:

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

Parameters

ch: char value i.e. a single character e.g. ‘a’

fromIndex: index position from where index of the char value or substring is retured

substring: substring to be searched in this string


Returns

index of the string


Java String indexOf() method example

  1. public class IndexOfExample{
  2. public static void main(String args[]){
  3. String s1=“this is index of example”;
  4. //passing substring
  5. int index1=s1.indexOf(“is”);//returns the index of is substring
  6. int index2=s1.indexOf(“index”);//returns the index of index substring
  7. System.out.println(index1+”  “+index2);//2 8
  8. //passing substring with from index
  9. int index3=s1.indexOf(“is”,4);//returns the index of is substring after 4th index
  10. System.out.println(index3);//5 i.e. the index of another is
  11. //passing char value
  12. int index4=s1.indexOf(‘s’);//returns the index of s char value
  13. System.out.println(index4);//3
  14. }}

Output:

2  8
5
3
PinIt
submit to reddit

Leave a Reply

Top