Skip to main content

Unit 2 · Selection and Iteration

String Traversal

Practice mode with 15 Java-focused questions, immediate answer checks, and explanations.

What string traversal covers

Traversing a String means looping an index from 0 while it is less than length() and examining each character with charAt. Because Strings are immutable, building a modified version means accumulating into a new String rather than editing in place. Common traversal jobs include counting occurrences, reversing text, filtering characters, and checking whether the text matches a pattern.

Where students lose points

Bounds errors dominate: using <= length() throws, and stopping at length() - 1 with a < test skips the final character. When comparing adjacent characters, students forget to shorten the loop bound by one and read past the end. Result accumulators also get initialized inside the loop, discarding everything built so far.

How it shows up on the AP exam

Unit 1 and Unit 2 combined, since traversal is where String methods meet iteration. This pairing is a standard FRQ setup and one of the most reliable long-tail MCQ topics.

For practice use only.

String Traversal MCQ Practice

AP CSA String traversal practice: looping over characters, building results with concatenation, counting matches, and staying inside valid index bounds.

Question 1 of 15

Answered 0 of 15

Choose one answer.

Which option matches the complete output produced by this segment?

String word = "level";
int matches = 0;
int position = 0;
while (position < word.length())
{
    String piece = word.substring(position, position + 1);
    if (piece.equals("l"))
    {
        matches++;
    }
    position++;
}
System.out.print(matches);
Choose one answer.