Java String lastIndexOf() Method Example

There are 4 types of a lastIndexOf method in java. The signature of lastIndexOf methods are given below:
  • lastIndexOf(int ch)  - Returns the index within this string of the last occurrence of the specified character.
  • lastIndexOf(int ch, int fromIndex)  - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
  • lastIndexOf(String str)  - Returns the index within this string of the last occurrence of the specified substring.
  • 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.
The main usage of lastIndexOf()  - Searches for the last occurrence of a character or substring.

Java String lastIndexOf() Method Example

This program demonstrates the usage of all 4  lastIndexOf()  methods.
public class LastIndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
         // method1
        int lastIndexOf = str.lastIndexOf('s');
        System.out.println(" last index of given character 's' in' " + " "+ str+"' ::  " + lastIndexOf);
         // method 2
        lastIndexOf = str.lastIndexOf("guides");
        System.out.println(" last index of given string 'guides' in' " + " "+ str+"' ::  " + lastIndexOf);
         // method 3
        lastIndexOf = str.lastIndexOf("guides", 4);
        System.out.println(" last index of guides in given  string " + " "+ str+" and from index  " + lastIndexOf);
         // method 4
        lastIndexOf = str.lastIndexOf('g', str.length());
        System.out.println(" last index of given char ::  " + lastIndexOf);
    }
}

Output:
 last index of given character 's' in'  javaguides':: 9 last index of given string 'guides' in'  javaguides':: 4 last index of guides in given string javaguides and from index 4 last index of given char:: 4 

Reference


Comments