Java String lastIndexOf()

The syntax of the String lastIndexOf() method either

string.lastIndexOf(int ch, int index)

or

string.lastIndexOf(string str, int index)

lastIndexOf() Parameters

To find the last index of a character, lastIndexOf() takes these two parameters:

  • ch - the character whose last index is to be found
  • index (optional) - if index is passed, the ch character is searched from start to this index

To find the last index of the specified substring within the string, lastIndexOf() takes these two parameters:

  • str - the string whose last index is to be found
  • index (optional) - if index is passed, the str string is searched from start to this index

lastIndexOf() Return Value

  • returns the index of the last occurrence of the specified character/string
  • returns -1 if the specified character/string is not found.

Example 1: Java String lastIndexOf()

Note: The character 'a' occurs multiple times in the "Learn Java" string. The lastIndexOf() method returns the index of the last occurrence of 'a' (which is 9).


Example 2: lastIndexOf() With fromIndex Parameter

Notes:

  • The last occurrence of 'r' in the "Learn Java programming" string is at index 15. However, str1.lastIndexOf('r', 4) searches the substring "Learn". The last index of 'r' in "Learn" is at index 3.
  • str1.lastIndexOf('r', 12) searches the substring "Learn Java pr". The last index of 'r' in "Learn Java pr" is at index 12.
  • str1.lastIndexOf("Java", 4) searches the substring "Learn". Since there is no "Java" in the "Learn" substring, the result is -1.

Recommended Reading: Java String indexOf()