`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
