Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lastindexof
method
java
strings

What is the lastIndexOf() method in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}

RELATED TAGS

lastindexof
method
java
strings
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring