Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the sense of method `int indexOf(String str, int fromIndex)`?

String str = "String in java is a sequence of characters java";
int i2 = str.lastIndexOf("java");
System.out.println(i2);
System.out.println(str.indexOf("java", 20));

In both cases the output is 43 (the index starting from the beginning of the literal).

According to docs the method int indexOf(String str, int fromIndex) returns "the index of the first occurrence of the specified substring, starting at the specified index".

If I understand it right it should return then 23 (logically), otherwise what is the sense of this method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your String the first occurrence of "java" starts at index 10. The second occurrence of "java" starts at index 43.

According to docs the method int indexOf(String str, int fromIndex) returns the index of the first occurrence of the specified substring, starting at the specified index.

It does return the index of the first occurrence of the substring starting at the specified index, but this does not mean the method will count the index starting from the specified index.

In short, the method will begin searching for the substring (in this case, "java") after the specified index, ignoring any previous matches. However, the returned index will still be counted from the beginning of the string, not from the specified index.

So:

  • first index of "java" -> 10
  • second index of "java" -> 43
  • specified index -> 20

The method will return 43.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading