Java String lastIndexOf(): Backward Search & Last Position Indexing

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().

1. Syntax & The Four Overloaded Signatures 🔝

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.

Java String lastIndexOf()

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'));  // -1

Terminal Output:

Last 'e': 17
Last 'o': 21
Last 'z': -1

3. Character Search with fromIndex Backward Bound 🔝

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));   // 4

Terminal Output:

From 22: 21
From 20: 9
From 5:  4

4. Finding the Last Substring Occurrence 🔝

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"));  // -1

Terminal Output:

Last 'co':   20
Last 'net':  16
Last 'java': -1

5. Substring Search with fromIndex Bound 🔝

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));   // -1

Terminal Output:

'co' from 20: 20
'co' from 19: 3
'co' from 2:  -1

6. High-Contrast: lastIndexOf() vs. indexOf() 🔝

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.

Java String indexOf()

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"));  // 20

Terminal Output:

First 'Java': 0
Last 'Java':  20

7. Production Recipe: Extracting File Extensions 🔝

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:

8. Practical Recipe: Splitting Folder Paths and File Names 🔝

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

9. Common Developer Pitfalls & Traps 🔝

The fromIndex Direction Trap

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.

Missing Extension Substring Off-By-One

If lastIndexOf('.') returns -1, calling str.substring(lastDot + 1) evaluates to str.substring(0), mistakenly returning the whole filename! Always check lastDot != -1.

10. Complete Compilable Java Program 🔝

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!

11. Frequently Asked Questions (FAQ) 🔝

What happens if fromIndex is greater than the string length?

If fromIndex >= length(), Java clamps it to length() - 1 and searches backward through the entire string without throwing an error.

What happens if fromIndex is negative?

If fromIndex < 0, there are no valid character positions to search backward, and lastIndexOf() immediately returns -1.

Is lastIndexOf() case-sensitive?

Yes. lastIndexOf() distinguishes uppercase and lowercase characters. To search case-insensitively, normalize both strings with toLowerCase().

What does lastIndexOf("") return?

Calling str.lastIndexOf("") returns the length of the string, or fromIndex if specified (capped at length()).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer