Java StringBuilder lastIndexOf() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.lastIndexOf(str) searches a StringBuilder from right to left and returns the starting index of the last occurrence of str, or -1 if not found.

Even though the search moves backward, the returned index still counts from 0 at the beginning of the builder. This makes it ideal for editing a file extension or swapping the final comma in a formatted list.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.lastIndexOf(...). No import is needed because java.lang is always visible.

Syntax

Search backward from the end with one argument, or from fromIndex with two.

Java
StringBuilder sb = new StringBuilder("a, b, c");
int last = sb.lastIndexOf(", ");      // 4
int prev = sb.lastIndexOf(", ", 3);   // 1
CallWhat it does
sb.lastIndexOf(".")Finds the rightmost dot (useful before replacing an extension).
sb.lastIndexOf(", ", cutoff)Finds the rightmost match starting at or before cutoff.
sb.lastIndexOf("x")Returns -1 if "x" never appears.

Like indexOf(), lastIndexOf() requires a String argument—passing a char literal will not compile.

Library declarations
Java
// java.lang.StringBuilder
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

Parameters

ParameterDescription
str (String)Non-null substring to locate.
fromIndex (int)Optional rightmost starting index for the backward search.

Return Value

Return ValueDescription
intZero-based starting index of the last match, or -1 if none exists.

Compare with Similar Methods

Searching and editing from the right:

MethodHow it differs
indexOf(str)Searches forward from the left for the earliest match.
replace(start, end, str)Replaces text at the index returned by lastIndexOf().
delete(start, end)Deletes from the found trailing position to the end.
substring(start)Extracts the tail after the last separator as a String.

Java Examples

Example 1 — Change the Last Comma Into "and" In Place

Format a human-readable list by finding the rightmost ", " and replacing it with " and ".

Java
public class StringBuilderLastIndexOfComma {
    public static void main(String[] args) {
        StringBuilder list = new StringBuilder("red, green, blue");
        int lastComma = list.lastIndexOf(", ");
        if (lastComma != -1) {
            list.replace(lastComma, lastComma + 2, " and ");
        }
        System.out.println(list.toString());
    }
}

How It Works

  1. Scan from the right. lastIndexOf(", ") skips the first comma at index 3 and returns index 10.
  2. Replace two characters. Swapping indexes 10..12 replaces only that final comma-space pair.
  3. Builder grows automatically. Inserting five characters in place of two yields red, green and blue.

Example 2 — Update a File Extension Using lastIndexOf(".")

Find the last dot (not an earlier folder dot) to change a filename extension safely.

Java
public class StringBuilderLastIndexOfExt {
    public static void main(String[] args) {
        StringBuilder file = new StringBuilder("v1.0/archive.tar.gz");
        int dot = file.lastIndexOf(".");
        int slash = file.lastIndexOf("/");
        if (dot > slash) {
            file.replace(dot, file.length(), ".zip");
        }
        System.out.println("Updated: " + file);
    }
}

How It Works

  1. Rightmost dot. lastIndexOf(".") ignores v1.0 and .tar, returning index 16 (.gz).
  2. Ensure dot is in filename. Checking dot > slash confirms the dot comes after the last folder separator.
  3. Rewrite extension in place. Replacing from index 16 to length() changes .gz to .zip.

Example 3 — Use fromIndex Cutoffs and Handle null

Limit a backward search to an earlier part of the builder, test negative fromIndex, and catch NullPointerException.

Java
public class StringBuilderLastIndexOfRules {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("ab-ab-ab");
        System.out.println("Last overall:  " + sb.lastIndexOf("ab"));
        System.out.println("Before idx 5:  " + sb.lastIndexOf("ab", 5));
        System.out.println("Negative idx:  " + sb.lastIndexOf("ab", -1));
        System.out.println("Empty needle:  " + sb.lastIndexOf(""));

        try {
            sb.lastIndexOf(null);
        } catch (NullPointerException e) {
            System.out.println("null needle threw NullPointerException");
        }
    }
}

How It Works

  1. Search whole buffer. Starting from the end finds the third "ab" at index 6.
  2. Cutoff excludes index 6. Passing fromIndex = 5 stops before the last match and finds the middle one at index 3.
  3. Negative or empty rules. fromIndex = -1 returns -1, "" returns length() (8), and null throws NullPointerException.

Frequently Asked Questions

No. It searches backward from the right, but the returned index is always counted from 0 at the left.
It returns sb.length() (unless fromIndex is negative, which returns -1).
It returns -1 without throwing.
It fails to compile because StringBuilder.lastIndexOf only accepts a String. Pass "." instead.
Compare sb.indexOf(sub) and sb.lastIndexOf(sub): if both are not -1 and are equal, it appears once.

Next: length()

Return the current number of UTF-16 char units stored in the builder.

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.

11 people found this page helpful