Java String lastIndexOf() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, lastIndexOf() returns the zero-based position of the last occurrence of a character or substring in a string. It works like indexOf(), but searches from the right end towards the start. If nothing matches, it returns -1.

It is the natural tool for anything that sits at the end of text: the extension after the last dot in "report.final.pdf", the file name after the last slash in a path, or the final word of a sentence.

lastIndexOf() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.lastIndexOf(...); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.

Syntax

Pass a char or a String; optionally pass the index where the backward search starts.

java
int dot   = fileName.lastIndexOf('.');      // last '.'
int slash = path.lastIndexOf("/");          // last "/"
int prev  = text.lastIndexOf("ab", 5);      // last "ab" starting at or before 5
CallWhat it does
"a/b/c".lastIndexOf('/')Returns 3, the right-most slash.
"abcabc".lastIndexOf("abc")Returns 3.
"abcabc".lastIndexOf("abc", 2)Only matches starting at index 2 or earlier count: returns 0.
"abc".lastIndexOf('z')Returns -1.

With fromIndex the search runs backwards: a match counts only if it starts at fromIndex or earlier. A fromIndex at or past the end searches the whole string; a negative one returns -1. No overload throws for a bad index.

Library declarations
java
public int lastIndexOf(int ch);
public int lastIndexOf(int ch, int fromIndex);
public int lastIndexOf(String str);
public int lastIndexOf(String str, int fromIndex);

Parameters

ParameterDescription
chThe character (or Unicode code point) to look for.
strThe substring to look for. Must not be null.
fromIndexOptional. The highest start index a match may have. Defaults to the end of the string.

Return Value

Return ValueDescription
intThe index where the last match starts.
-1When there is no match.

Java Examples

Example 1 — Get the Extension After the Last Dot

A file name can contain several dots. Compare the first dot with the last one.

java
public class LastIndexOfExtension {
    public static void main(String[] args) {
        String file = "report.final.pdf";

        int firstDot = file.indexOf('.');
        int lastDot = file.lastIndexOf('.');

        System.out.println("first dot: " + firstDot);
        System.out.println("last dot:  " + lastDot);
        System.out.println("extension: " + file.substring(lastDot + 1));
    }
}

How It Works

  1. Two dots, two answers. indexOf('.') stops at 6 (after "report"), but the extension is not there.
  2. Scan from the right. lastIndexOf('.') returns 12, the dot just before "pdf".
  3. Slice after it. substring(13) yields "pdf"; file itself still holds the full name.

Example 2 — Split a Path into Folder and File Name

Use the last '/' to separate the directory part from the file name.

java
public class LastIndexOfPath {
    public static void main(String[] args) {
        String path = "/home/ada/docs/notes.txt";

        int slash = path.lastIndexOf('/');
        String folder = path.substring(0, slash);
        String name = path.substring(slash + 1);

        System.out.println("slash at: " + slash);
        System.out.println("folder:   " + folder);
        System.out.println("file:     " + name);
    }
}

How It Works

  1. Four slashes, one matters. The path has slashes at 0, 5, 9, and 14; only the right-most one separates the file name.
  2. Folder is everything before it. substring(0, 14) keeps "/home/ada/docs" without the trailing slash.
  3. File is everything after it. substring(15) returns "notes.txt". For real file systems, the Files API offers ready-made helpers.

Example 3 — List Every Match from Right to Left

Feed each result minus one back in as fromIndex to step backwards through all matches.

java
public class LastIndexOfBackward {
    public static void main(String[] args) {
        String s = "abcabcabc";

        int pos = s.lastIndexOf("abc");
        while (pos >= 0) {
            System.out.println("abc at " + pos);
            pos = s.lastIndexOf("abc", pos - 1);
        }
        System.out.println("lastIndexOf(\"abc\", 4) = " + s.lastIndexOf("abc", 4));
    }
}

How It Works

  1. Start at the end. Without fromIndex, the last "abc" begins at 6.
  2. Move the ceiling down. Passing pos - 1 allows only matches that start earlier, giving 3 and then 0; from -1 the method returns -1 and the loop ends.
  3. fromIndex limits the start, not the end. With 4, the match at 3 still counts even though it runs to index 5, so the answer is 3.

Frequently Asked Questions

The zero-based index where the last occurrence of the char or substring starts, or -1 if there is none.
The search goes backwards from fromIndex. A match counts only if it starts at fromIndex or before it, even if it extends past fromIndex.
Find the last dot with lastIndexOf('.'), check that it is not -1, then take substring(dot + 1).
Yes. "Data.CSV".lastIndexOf("csv") is -1. Lowercase both strings first with toLowerCase(Locale.ROOT) to ignore case.
indexOf() returns the first (left-most) match and lastIndexOf() returns the last (right-most) match. Both return -1 when nothing matches.

Next: length()

Get the number of UTF-16 chars in a string.

length() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful