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