Library contents

Java String.lastIndexOf

Locate the final occurrence of a character or substring, optionally searching backward from an offset.

A simple example

String.lastIndexOf

  1. Start with "aba", looking for a
  2. Do this Find the last match
  3. Result Index 2 (zero-based)
There are two matches. Searching from the right reaches the final a first.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("aba".lastIndexOf("a"));
    }
}
Output
2

Syntax

Java syntax
public int lastIndexOf(int ch)
JDK 21 method signatures (4)
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read the final extension of an invoice

A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.

From the programString file = "april.invoice.pdf"
Resultpdf
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String file = "april.invoice.pdf";
        System.out.println(file.substring(file.lastIndexOf('.') + 1));
    }
}
Output
pdf

The final dot separates the extension from the rest of the filename.

Advertisements

Locate the previous stop in a route

A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.

From the programString route = "A/B/C/D"
Result3
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String route = "A/B/C/D";
        System.out.println(route.lastIndexOf("/", 4));
    }
}
Output
3

Backward search from index four finds the slash before C.

Read a parcel sorting code

The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?

GivenNC-17
Worked result2

What to watch for

A missing match returns -1. Check that result before using it as an index.

Documentation for String.lastIndexOf