Course contentsShow
← Java
Lesson 2198 of 2,87043. String Handling in DepthFree lesson

indexOf with Starting Position: Searching from an Offset

Learn indexOf(String str, int fromIndex) to search for occurrences starting at a specific position.

indexOf with Starting Position: Searching from an Offset

You'll learn how to search for a substring starting from a specific index, enabling you to find multiple occurrences or skip already-processed text.

The Core Idea

You've already used indexOf(String str) to find the first occurrence of a substring. But what if you need to find the second occurrence? Or skip the first 10 characters before searching? That's where indexOf(String str, int fromIndex) comes in.

This overloaded version takes a starting position (fromIndex) and searches for the substring only from that point forward. Characters before fromIndex are completely ignored.

How It Works

String text = "Java is fun, Java is powerful";

// First occurrence of "Java"
int first = text.indexOf("Java");        // Returns 0

// Second occurrence: start searching AFTER the first match
int second = text.indexOf("Java", 5);    // Returns 13

The 5 tells indexOf to start looking at index 5, which skips past the first "Java" (at index 0-3).

Finding All Occurrences

This technique shines when you need to find every occurrence:

String message = "test and test and test";
int pos = 0;

while ((pos = message.indexOf("test", pos)) != -1) {
    System.out.println("Found at: " + pos);
    pos++; // Move past this match to find the next
}
// Output: Found at: 0, Found at: 9, Found at: 18

By updating pos after each match, you systematically walk through the string finding every instance.

Think of It Like...

Imagine reading a book with a bookmark. Regular indexOf always starts from page 1. With fromIndex, you're saying "start from my bookmark position" — you skip everything before it.

Key Takeaway:
Use indexOf(String str, int fromIndex) to search for substrings starting at a specific position, enabling multi-match searches and targeted text processing without re-scanning the entire string.