liveBook · Manning

indexOf method

As explained in 100 Java Mistakes and How to Avoid Them

The Java String.indexOf method returns the index of the first occurrence of a specified character or substring, or -1 when no occurrence exists.

`String.indexOf()` searches for a character or substring and returns its first index, or `-1` when no match exists. The two-argument overload resumes a search at `fromIndex`. Treat `-1` as a result that must be handled before using it in `substring()`, arithmetic, or loop control. section 6.11 section 6.9

Check before slicing

Searching for `=` and passing the result directly to `substring()` fails when the separator is absent: `-1` is not a valid substring boundary. Validate the search result first; then either return an explicit absence value or throw a domain-specific exception such as “Entry must have key and value.” Do not add an offset before testing: for `indexOf("//") + 2`, an absent marker becomes `1`, hiding the failed search. section 6.9

Keep two-argument calls in order

The overload is `indexOf(character, fromIndex)`, but both arguments may be `int`. Writing `s.indexOf(start, ']')` reverses them; it compiles and usually returns no result, while rare inputs can yield a wrong one. Use IDE parameter hints and tests for string-processing helpers; Error Prone can report this pattern as `IndexOfChar`. section 6.10 section 6.11

static String getBracketedSubstring(String s) {
  int start = s.indexOf('[');
  if (start == -1) return null;
  int end = s.indexOf(start, ']');    #1
  if (end == -1) return null;
  return s.substring(start, end + 1);
}

The bracket extractor isolates the swapped-argument failure: the second search should look for `']'` beginning at `start`, not search for a character whose code point is `start`. section 6.10

Advance every search loop

Repeated searches commonly use `pos = str.indexOf('%', pos)`. Every nonterminal loop path must advance `pos` or return. A parser for `%d` that only advances after escaped `%%` repeatedly finds the same `%` in `%s` and never terminates. High line, instruction, and mutation coverage can still miss that path; static analyzers may be silent. section 3.8

Use these rules when consuming an index result:

  • Check the raw result against `-1` before offsets or substring boundaries. section 6.11 section 6.9
  • Make absent input behavior explicit: reject it, return an absence value, or document an intentional fallback. section 6.9
  • For iterative searches, ensure each path changes the start position or exits. section 3.8
  • Read parameter-name hints and add simple tests for normal and missing-delimiter inputs. section 6.10

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains return-value handling, overload ordering, and loop progress through focused failure cases; does not detail String internals.
Examples
Uses key-value entries, filenames, comment markers, bracketed substrings, and escaped `%d` format specifiers.
What it assumes
Assumes Java string APIs and control flow, then teaches defensive handling of search results and search positions.
What you can do after
Diagnose/debug with it by recognizing unchecked `-1`, reversed overload arguments, and repeated searches that never advance.
How it connects
Connects `indexOf()` to `lastIndexOf()`, `substring()`, string parsing, test coverage, mutation testing, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.