Understanding substring Indices and Off-by-One Errors
You'll learn how to interpret substring indices correctly to avoid the most common string slicing mistakes.
Java's substring(int beginIndex, int endIndex) uses inclusive-start, exclusive-end semantics. This means the character at beginIndex is included, but the character at endIndex is not. Think of it like a fence: you're marking the posts around the section you want, not the section itself.
The Index Model
Consider the string "HELLO":
Indices: 0 1 2 3 4 5
H E L L O
↑ ↑
start=0 end=5
To extract "HELLO", you write substring(0, 5) — start at index 0, stop before index 5. The length is always endIndex - beginIndex.
Common Off-by-One Errors
Error 1: Forgetting exclusivity
String text = "HELLO";
String last = text.substring(4, 5); // "O" — correct
String wrong = text.substring(4, 4); // "" — empty! Start equals end.
Error 2: Using length as end index for "everything after"
String text = "HELLO";
// Want "LLO" starting at index 2
String right = text.substring(2); // Correct: single-arg form
String also = text.substring(2, 5); // Also correct
String oops = text.substring(2, 6); // StringIndexOutOfBoundsException!
Error 3: Extracting a single character
String text = "HELLO";
String e = text.substring(1, 2); // "E" — end is always start + 1 for single char
Mental Model
The end index is where to stop, not what to include. When extracting n characters starting at i, use substring(i, i + n).
Key Takeaway: The substring(start, end) method includes the character at start but excludes end—the length is always end - start, and failing to account for this exclusivity causes most substring bugs.