Course contentsShow
← Java
Lesson 2199 of 2,87043. String Handling in DepthFree lesson

The lastIndexOf Method: Searching Backwards

Use lastIndexOf to find the last occurrence of a character or substring in a string.

The lastIndexOf Method: Searching Backwards

What you'll learn: How to find the last occurrence of a character or substring within a string by searching from the end toward the beginning.

The Core Idea

While indexOf searches forward through a string from left to right, lastIndexOf does the opposite—it searches backward from right to left. This is invaluable when you need to find the final occurrence of a character or substring, such as locating the last dot in a filename or the final slash in a file path.

Like indexOf, lastIndexOf returns the index of the match (or -1 if not found), but it gives you the rightmost occurrence.

Basic Usage

String text = "hello world hello";

// Find last occurrence of 'o'
int lastO = text.lastIndexOf('o');  // Returns 14

// Find last occurrence of "hello"
int lastHello = text.lastIndexOf("hello");  // Returns 12

// Not found case
int notFound = text.lastIndexOf('z');  // Returns -1

Searching Backwards from a Position

Just as indexOf can start searching from an offset, lastIndexOf can search backward from a specified position:

String path = "docs/files/data.txt";

// Find last '/' starting from the end
int lastSlash = path.lastIndexOf('/');  // Returns 10

// Find last '/' before position 10
int previousSlash = path.lastIndexOf('/', 9);  // Returns 4

The second parameter limits how far right the search will consider—it searches from that position backward toward index 0.

Practical Example

String filename = "report.backup.txt";

// Get the file extension
int lastDot = filename.lastIndexOf('.');
String extension = filename.substring(lastDot + 1);  // "txt"

Key Takeaway: lastIndexOf searches a string from right to left to find the final occurrence of a character or substring, returning its index or -1 if not found—essential for parsing paths, extensions, and repeated delimiters.