Java StringBuilder indexOf() Method

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

Definition

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

Pass an optional fromIndex to start searching later in the buffer—handy when looping through multiple matches or pairing with replace() or delete().

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.indexOf(...). No import is needed because java.lang is always visible.

Syntax

Search the whole builder with one argument, or start at fromIndex with two.

Java
StringBuilder sb = new StringBuilder("one, two, one");
int first = sb.indexOf("one");         // 0
int next  = sb.indexOf("one", 1);      // 10
boolean has = sb.indexOf("two") != -1; // true
CallWhat it does
sb.indexOf("word")First index of "word", or -1 if absent.
sb.indexOf("word", pos)First match at or after pos, or -1.
sb.indexOf("key") != -1Replaces contains(), which StringBuilder lacks.

Unlike String, StringBuilder has no indexOf(char) overload and no contains() method: always pass a String (",", not ',') and check != -1.

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

Parameters

ParameterDescription
str (String)Non-null substring to search for.
fromIndex (int)Optional index where the forward search starts.

Return Value

Return ValueDescription
intZero-based starting index of the first match, or -1 if not found.

Compare with Similar Methods

Searching and editing inside a StringBuilder:

MethodHow it differs
lastIndexOf(str)Searches backward from the end (or fromIndex) for the last match.
replace(start, end, s)Uses the found index to replace a substring in place.
delete(start, end)Uses the found index to remove a substring in place.
String.contains(seq)Returns a boolean on immutable strings without giving the index.

Java Examples

Example 1 — Check With indexOf() Before Replacing a Word

Use indexOf() != -1 instead of contains(), then pass the match index directly to replace().

Java
public class StringBuilderIndexOfEdit {
    public static void main(String[] args) {
        StringBuilder log = new StringBuilder("Status: WARN (disk 85%)");
        String target = "WARN";
        int idx = log.indexOf(target);

        if (idx != -1) {
            log.replace(idx, idx + target.length(), "OK");
        }
        System.out.println(log.toString());
        System.out.println("Has ERROR? " + (log.indexOf("ERROR") != -1));
    }
}

How It Works

  1. Locate marker. log.indexOf("WARN") scans left to right and finds index 8.
  2. Check before editing. Guarding with idx != -1 ensures replace() never receives -1.
  3. Test missing key. Searching for "ERROR" returns -1, so != -1 evaluates to false.

Example 2 — Find Every Occurrence With fromIndex

Advance pos after each match so a single loop lists every occurrence inside a builder.

Java
public class StringBuilderIndexOfAll {
    public static void main(String[] args) {
        StringBuilder text = new StringBuilder("ha-ha-ha");
        String needle = "ha";
        int pos = 0;

        while ((pos = text.indexOf(needle, pos)) != -1) {
            System.out.println("Found at index " + pos);
            pos += needle.length();
        }
    }
}

How It Works

  1. Start at 0. First indexOf("ha", 0) returns index 0.
  2. Skip matched length. Advancing pos += 2 moves past the current match to index 2, finding the next "ha" at 3.
  3. Loop terminates cleanly. After index 6, searching from index 8 returns -1 and exits the loop.

Example 3 — Case Sensitivity, fromIndex Clamping, and null Input

See how case differences return -1, negative fromIndex clamps to 0, and null throws.

Java
public class StringBuilderIndexOfRules {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("CodeToFun");
        System.out.println("Lowercase match: " + sb.indexOf("code"));
        System.out.println("fromIndex -5:    " + sb.indexOf("To", -5));
        System.out.println("fromIndex 99:    " + sb.indexOf("To", 99));

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

How It Works

  1. Exact case required. "code" fails to match "Code", returning -1.
  2. Clamped negative start. Passing -5 quietly starts searching from index 0, locating "To" at index 4.
  3. Null rejected. Passing null throws NullPointerException instead of returning -1.

Frequently Asked Questions

No. Check sb.indexOf(text) != -1 (or >= 0) to test whether a substring exists inside a StringBuilder.
No. StringBuilder only defines indexOf(String) and indexOf(String, int). Pass a single-character String like "a" instead.
It returns -1.
Yes. Uppercase and lowercase letters must match exactly.
It throws NullPointerException.

Next: insert()

Insert text, numbers, characters, or arrays at any offset from 0 to length() inclusive.

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

9 people found this page helpful