Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

4.4: String Traversal

Traverse indices less than length, extract each one-character substring, and use equals for content comparison.

College Board Unit 1

How it works

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.

Choose bounds that match the comparison: adjacent-pair loops must stop one index early.

Common error

Running an adjacent-pair loop to the final index, which reads past the end.

Worked example

Java

String text = "level";
int count = 0;
for (int i = 0; i < text.length(); i++) {
    if (text.substring(i, i + 1).equals("e")) count++;
}
System.out.println(count);

Output

2

The traversal visits all five indices and counts matches at indices 1 and 3.

Exercises

4.4.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

String text = "dog";
String result = "";
for (int i = text.length() - 1; i >= 0; i--) {
    result += text.substring(i, i + 1);
}
System.out.println(result);
Show solution

Output

god

The loop reads indices 2, 1, and 0 in that order.

4.4.2 · Write code

Write public static String removeA(String text), returning the text with every lowercase "a" omitted. Preserve the order of the remaining characters.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static String removeA(String text) {
    String result = "";
    for (int i = 0; i < text.length(); i++) {
        String letter = text.substring(i, i + 1);
        if (!letter.equals("a")) result += letter;
    }
    return result;
}

Check your code

Java

System.out.println(removeA("banana"));
System.out.println("[" + removeA("") + "]");

Expected output

bnn
[]
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic