Java String lastIndexOf() Method

If you want to know the index of last occurrence of a character or substring in a String, then String class in Java provides a method lastIndexOf() to know the index. Java String lastIndexOf() method is used to find the  index of last occurrence of character or a substring in a specified string.

There are 4 variations of lastIndexOf() method in String class. Let’s see each of these.

lastIndexOf(int ch):

The syntax of this String lastIndexOf() method is:

where ch is character. This method returns the index of the last occurrence of the specified character in the String. If specified character is not found then -1 is returned. The String is searched backwards starting at the last character.

lastIndexOf(int ch, int startIndex):

The syntax of this String lastIndexOf() method is:

where ch is character and startIndex is the index to start the search from. This method returns index of the last occurrence of the specified character after the startIndex. If specified character is not found then -1 is returned.

lastIndexOf(String str):

The syntax of this String lastIndexOf() method is:

where str is the substring that you want to search in the String. This method returns the index of the last occurrence of the specified substring in the String. If specified substring is not found then -1 is returned.

lastIndexOf(String str, int startIndex):

The syntax of this String lastIndexOf() method is:

where str is the substring that you want to search in the String and startIndex is the index to start the search from. This method returns the index of the last occurrence of the specified substring after the startIndex. If specified character is not found then -1 is returned.

Example:

Let’s see the String lastIndexOf() method with an example.

Output:

You can also learn about String indexOf() method at Java String indexOf() Method.