Videos
The substring is always matched in the forward direction for String#indexOf or String#lastIndexOf. Therefore, a1.lastIndexOf(s1) and a1.lastIndexOf(s1, a1.lastIndexOf(s1)) will always return the same index.
String a1 = "1231231";
String s1 = "23";
int lastIndex = a1.lastIndexOf(s1); // 4
System.out.println(lastIndex);
System.out.println(a1.lastIndexOf(s1, lastIndex)); // 4
int secondLastIndex = a1.lastIndexOf(s1, lastIndex - 1); //1
System.out.println(secondLastIndex);
It sounds to me like you are interpreting last index as previous index where it's actually the index of the last occurrence (or perhaps final occurrence) of that substring within the source string. If the substring's last position starts at n then as long as the fromIndex position is between 0 and n inclusive, you will return n.
From the JavaDoc:
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
Based on the source found here, it appears as if lastIndexOf does traverse from the end of the string, towards the beginning. An excerpt is posted below for convenience; note the decrement operations as it is keeping track of i and j to find the last match.
startSearchForLastChar: while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}