How to Use LastIndexOf() in Java


This example is to show how to use lastIndexOf() in Java.

Source Code

package com.beginner.examples;

public class LastIndexOfExample {
	 
    public static void main(String a[]){
     
        String str = "Java example";
        //lastIndexOf() gives last occurence based on a specific position
        System.out.println("Char 'J' at last occurance is : " + str.lastIndexOf('J'));
        System.out.println("String 'example' at last occurance is : " + str.lastIndexOf("example"));
        System.out.println("First occurance of String 'example' from 2th index backwards is : " + str.lastIndexOf("example" , 2));
    }
}

Output:

Char 'J' at last occurance is : 0
String 'example' at last occurance is : 5
First occurance of String 'example' from 2th index backwards is : -1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments