Unit 2 Cycle 2 Day 11: Error: Loop Modifying Collection

Unit 2 Advanced (Cycle 2) Day 11 of 28 Advanced

Error: Loop Modifying Collection

Section 2.13 — Informal Code Analysis

Key Concept

A common error pattern involves modifying a collection or string while iterating over it. While the AP CSA exam does not use iterators, the concept appears when a loop processes a string and the processing changes the string's length. For example, removing characters from a string inside a for loop that uses the original length causes the loop to access indices beyond the shortened string. The safe approach is to build a new string rather than modifying the original, or to iterate backward when removing elements.

A method is intended to count even numbers in a string of digits.

public static int countEven(String digits) { int count = 0; for (int i = 0; i <= digits.length(); i++) { int d = Integer.parseInt(digits.substring(i, i + 1)); if (d % 2 == 0) { count++; } } return count; }

The call countEven("1234") causes an error. What is the fix?

Answer: (A) Change i <= to i <

When i = digits.length() (which is 4), substring(4, 5) throws StringIndexOutOfBoundsException because the string only has indices 0-3. Changing <= to < prevents i from reaching the length.

Why Not the Others?

(B) Starting at i=1 would skip the first digit, which is not the intended behavior.

(C) This would count odd numbers instead of even numbers, changing the logic.

(D) charAt(i) returns a char, which cannot be directly used with Integer.parseInt.

Common Mistake

i <= length allows i to equal the length, which causes an out-of-bounds error on the substring call. Always use i < length for string traversal.

AP Exam Tip

The standard string traversal bounds are i = 0; i < s.length(). Using <= is almost always a bug.

Review this topic: Section 2.13 — Informal Code Analysis • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.