The String.lastIndexOf() method searches backward from right to left and returns the index of the last occurrence of a character or substring, returning -1 if not found.
Backward Searching & File Parsing: While indexOf() scans forward from the start, lastIndexOf() begins at the end of the text. It is ideal for extracting file extensions, path separators, and trailing delimiters with substring(). To inspect individual characters, see charAt(), or measure string size with length().
Java provides four overloads in java.lang.String to support character and substring searches scanning backward from an optional starting boundary:
// 4 Overloaded signatures of lastIndexOf() in java.lang.String
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
| Signature | Target Type | Backward Search Boundary |
|---|---|---|
lastIndexOf(int ch) |
Single character | Searches backward from str.length() - 1 to index 0. |
lastIndexOf(int ch, int fromIndex) |
Single character | Searches backward from fromIndex down to index 0. |
lastIndexOf(String str) |
Substring sequence | Searches backward from str.length() to index 0. |
lastIndexOf(String str, int fromIndex) |
Substring sequence | Searches backward starting at or before fromIndex. |
When searching for a character, Java scans backward from the end and returns its 0-based index counting from the left:
String str = "Welcome to plus2net.com";
System.out.println("Last 'e': " + str.lastIndexOf('e')); // 17
System.out.println("Last 'o': " + str.lastIndexOf('o')); // 21
System.out.println("Last 'z': " + str.lastIndexOf('z')); // -1Terminal Output:
Last 'e': 17
Last 'o': 21
Last 'z': -1
In lastIndexOf(), the fromIndex parameter acts as an upper ceiling. Java only searches positions at or before fromIndex:
String str = "Welcome to plus2net.com";
System.out.println("From 22: " + str.lastIndexOf('o', 22)); // 21
System.out.println("From 20: " + str.lastIndexOf('o', 20)); // 9
System.out.println("From 5: " + str.lastIndexOf('o', 5)); // 4Terminal Output:
From 22: 21
From 20: 9
From 5: 4
Passing a String argument locates the starting index of the last matching multi-character sequence:
String text = "Welcome to plus2net.com";
System.out.println("Last 'co': " + text.lastIndexOf("co")); // 20
System.out.println("Last 'net': " + text.lastIndexOf("net")); // 16
System.out.println("Last 'java': " + text.lastIndexOf("java")); // -1Terminal Output:
Last 'co': 20
Last 'net': 16
Last 'java': -1
Restricting the search ceiling with fromIndex allows locating preceding instances of repeated words:
String text = "Welcome to plus2net.com";
System.out.println("'co' from 20: " + text.lastIndexOf("co", 20)); // 20
System.out.println("'co' from 19: " + text.lastIndexOf("co", 19)); // 3
System.out.println("'co' from 2: " + text.lastIndexOf("co", 2)); // -1Terminal Output:
'co' from 20: 20
'co' from 19: 3
'co' from 2: -1
Comparing forward and backward searching side by side illustrates how search direction alters results:
| Feature | str.lastIndexOf(...) |
str.indexOf(...) |
|---|---|---|
| Search Direction | Backward (Right to Left). | Forward (Left to Right). |
| Default Start | End of string (length() - 1). |
Beginning of string (index 0). |
| fromIndex Role | Upper ceiling (scans backward to 0). |
Lower floor (scans forward to end). |
| Returned Position | Index of last occurrence. | Index of first occurrence. |
String sentence = "Java is powerful and Java is fast";
System.out.println("First 'Java': " + sentence.indexOf("Java")); // 0
System.out.println("Last 'Java': " + sentence.lastIndexOf("Java")); // 20Terminal Output:
First 'Java': 0
Last 'Java': 20
Because filenames can contain multiple periods (e.g. archive.tar.gz), lastIndexOf('.') is the standard for obtaining the true final extension:
public class FileExtensionExtractor {
public static String getFileExtension(String filename) {
if (filename == null) return "";
int lastDot = filename.lastIndexOf('.');
if (lastDot == -1 || lastDot == filename.length() - 1) {
return "";
}
return filename.substring(lastDot + 1);
}
public static void main(String[] args) {
System.out.println("report.pdf: " + getFileExtension("report.pdf")); // pdf
System.out.println("archive.tar.gz: " + getFileExtension("archive.tar.gz")); // gz
System.out.println("README: " + getFileExtension("README")); // (empty)
}
}Terminal Output:
report.pdf: pdf
archive.tar.gz: gz
README:
Locating the last slash separator in file paths isolates directory hierarchies from file names:
String path = "/var/www/html/plus2net/index.php";
int lastSlash = path.lastIndexOf('/');
if (lastSlash != -1) {
String folder = path.substring(0, lastSlash);
String file = path.substring(lastSlash + 1);
System.out.println("Folder: " + folder);
System.out.println("File: " + file);
}Terminal Output:
Folder: /var/www/html/plus2net
File: index.php
In indexOf(), fromIndex searches forward towards the end. In lastIndexOf(), fromIndex searches backward towards 0. If you pass a fromIndex smaller than the match position, lastIndexOf() returns -1.
If lastIndexOf('.') returns -1, calling str.substring(lastDot + 1) evaluates to str.substring(0), mistakenly returning the whole filename! Always check lastDot != -1.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringLastIndexOfFullDemo {
public static void main(String[] args) {
String data = "alpha/beta/gamma/delta";
int lastSlash = data.lastIndexOf('/');
if (lastSlash == 16) {
System.out.println("Check 1 Passed: Last slash found at index 16.");
}
int prevSlash = data.lastIndexOf('/', 15);
if (prevSlash == 10) {
System.out.println("Check 2 Passed: Previous slash found at index 10.");
}
int missing = data.lastIndexOf("omega");
if (missing == -1) {
System.out.println("Check 3 Passed: Missing term returned -1.");
}
System.out.println("All String.lastIndexOf() tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Last slash found at index 16.
Check 2 Passed: Previous slash found at index 10.
Check 3 Passed: Missing term returned -1.
All String.lastIndexOf() tests passed successfully!
If fromIndex >= length(), Java clamps it to length() - 1 and searches backward through the entire string without throwing an error.
If fromIndex < 0, there are no valid character positions to search backward, and lastIndexOf() immediately returns -1.
Yes. lastIndexOf() distinguishes uppercase and lowercase characters. To search case-insensitively, normalize both strings with toLowerCase().
Calling str.lastIndexOf("") returns the length of the string, or fromIndex if specified (capped at length()).
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.