Unit 1 Cycle 2 Day 12: Error Spotting: String Index Bounds
Share
Error Spotting: String Index Bounds
Section 1.10 — Strings: Methods
Key Concept
String index bounds errors occur when code accesses a character position that does not exist. Valid indices for a string of length n range from 0 to n - 1. The substring(start, end) method requires 0 <= start <= end <= length. Common AP exam errors include using s.substring(0, s.length() + 1), accessing charAt(s.length()), or not handling the case when indexOf() returns -1 and that value is used as a substring index.
Consider the following code segment.
Which line will cause a runtime error?
Answer: (C) Line 3
Index "JAVA": J(0) A(1) V(2) A(3). Length is 4.
Line 1: substring(1, 3) = "AV". Valid (indices 1 and 2).
Line 2: substring(4) = "". Valid. When start equals length, it returns an empty string.
Line 3: substring(0, 5) throws StringIndexOutOfBoundsException. The end index 5 exceeds the string length of 4.
Line 4: indexOf("VA") = 2. Valid. Returns -1 if not found, never throws an exception.
Why Not the Others?
(A) substring(1, 3) is valid. Both indices are within bounds (0 to 4 for end index).
(B) substring(4) on a 4-character string returns "". The start index can equal the length, which gives an empty string.
(D) indexOf never throws an exception. It returns -1 if the substring is not found.
Common Mistake
The tricky part is Line 2 vs Line 3. substring(length) is valid and returns an empty string. But substring(0, length + 1) is invalid because the end index exceeds the string length. The maximum valid end index for substring is length().
AP Exam Tip
Valid ranges for substring(start, end): 0 <= start <= end <= length(). For substring(start): 0 <= start <= length(). When start equals length, you get an empty string. When end exceeds length, you get an exception.