What is the lastIndexOf() method in Java?

The lastIndexOf() method in Java returns the index of the last occurrence of a given character or substring​. If the character or the substring is not found, ​ the ​function returns 1-1.

Syntax

svg viewer

Code

The following code snippet finds the last index of a character in a string:

import java.util.*;
class Program {
public static void main( String args[] ) {
String str = "educative";
int lastIndex = str.lastIndexOf('e');
System.out.println("The last index of this character is: " + lastIndex);
}
}

The last index of the occurrence of a sub-string can be searched as follows:

import java.util.*;
class Program {
public static void main( String args[] ) {
String str = "Welcome to educative.";
int lastIndex = str.lastIndexOf("to");
System.out.println("The last index of this sub-string is: " + lastIndex);
}
}

The optional argument can limit the search to only a part of the string; here is how it is used:

import java.util.*;
class Program {
public static void main( String args[] ) {
String str = "welcome to educative!";
// The string is only searched backwards from the 9th char.
int lastIndex = str.lastIndexOf('e', 9);
System.out.println("The last index of this character is: " + lastIndex);
// The string is only searched backwards from the 14th char.
lastIndex = str.lastIndexOf('e', 14);
System.out.println("The last index of this character is: " + lastIndex);
}
}
Copyright ©2024 Educative, Inc. All rights reserved