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

The indexOf Method: Finding Character Positions

Use indexOf(int ch) and indexOf(String str) to locate the first occurrence of characters or substrings.

The indexOf Method: Finding Character Positions

What you'll learn: How to locate the first occurrence of a character or substring within a String using the indexOf method.

The Core Idea

Think of indexOf as a search tool that scans through a String from left to right, looking for the first match. When it finds what you're searching for, it returns the index position (remember, indices start at 0). If it doesn't find anything, it returns -1 as a signal that the search failed.

Java provides two primary versions:

  • indexOf(int ch) — searches for a single character
  • indexOf(String str) — searches for a substring

How It Works

When you call indexOf, the String examines each character position sequentially until it finds a match or reaches the end. The return value tells you where the match begins:

String message = "Hello World";

// Finding a character
int pos1 = message.indexOf('o');  // Returns 4 (first 'o')
int pos2 = message.indexOf('W');  // Returns 6

// Finding a substring
int pos3 = message.indexOf("World");  // Returns 6
int pos4 = message.indexOf("Java");   // Returns -1 (not found)

// Character not present
int pos5 = message.indexOf('z');  // Returns -1

The Return Value Matters

Always check if indexOf returns -1 before using the result:

String filename = "report.pdf";
int dotPosition = filename.indexOf('.');

if (dotPosition != -1) {
    String extension = filename.substring(dotPosition + 1);
    // Safe to use the index
}

Key Takeaway: indexOf returns the zero-based position of the first occurrence of a character or substring, or -1 if not found—making it essential for search operations and parsing tasks.