AP CSA String Traversal

String Traversal in AP CSA: Complete Guide (2025-2026)

String traversal in AP CSA means iterating over a String character by character using a loop, and it is tested in both Unit 2 MCQ questions and FRQ solutions on the AP exam. Java Strings are zero-indexed: the first character is at index 0, the last is at index length() - 1. The key methods you must know are charAt(i), substring(a,b), length(), and indexOf(str). Every one of these methods appears regularly on the AP CSA exam.

💻 Code Examples — Predict First

Before running each example, write down your prediction. This is the single most effective AP exam study technique.

🤔 Predict the output before running:

Example 1: Print Each Character
public class Main {
    public static void main(String[] args) {
        String word = "hello";
        for (int i = 0; i < word.length(); i++) {
            System.out.print(word.charAt(i) + " ");
        }
    }
}
Running…

h e l l o — Loop runs i=0 to i=4 (length=5, condition i<5). charAt(i) returns the character at each index.

🤔 Predict the output before running:

Example 2: Count Vowels
public class Main {
    public static void main(String[] args) {
        String s = "banana";
        int vowels = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
                vowels++;
            }
        }
        System.out.println(vowels);
    }
}
Running…

3 — 'banana' has vowels at indices 1(a), 3(a), 5(a). Counter increments 3 times.

🤔 Predict the output before running:

Example 3: Reverse a String
public class Main {
    public static void main(String[] args) {
        String s = "abcde";
        String result = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            result += s.charAt(i);
        }
        System.out.println(result);
    }
}
Running…

edcba — Loop starts at last index (length-1=4) and counts down to 0. Each character is appended to build the reversed string.

❌ Common Pitfalls

These are the mistakes students most often make on the AP CSA exam with String traversal AP CSA. Study them carefully.

1
⚠ Using <= instead of < with length()

The last valid index is length()-1. Using i <= word.length() causes a StringIndexOutOfBoundsException on the extra iteration. Always use i < word.length().

for (int i=0; i<=word.length(); i++) // THROWS EXCEPTION
    word.charAt(i); // crashes when i == length
2
⚠ Confusing substring(a,b) end index

substring(a,b) returns characters from index a up to but NOT including index b. So "hello".substring(1,3) returns "el", not "ell". The AP exam tests this boundary every year.

"abcde".substring(1, 4) // returns "bcd" (NOT "bcde")
3
⚠ Using == to compare characters vs Strings

charAt(i) returns a char primitive, so == is correct for single-character comparison. But comparing two String objects requires .equals(). Mixing these up is a frequent AP trap.

4
⚠ Off-by-one in reverse traversal

When traversing backwards, the starting index must be length()-1, NOT length(). Starting at length() causes an immediate exception on the first call to charAt().

for (int i=s.length(); i>=0; i--) // CRASHES on first iteration
    s.charAt(i); // index length is out of bounds
🎓 AP Exam Tip

AP CSA FRQs frequently ask you to build a new String by traversing an existing one. Always initialize the result String to an empty string ("") before the loop, then use string concatenation inside. Returning before the loop or forgetting the initialization are the two most common FRQ errors.

⚠ Watch Out!

substring(a,b) has length b − a. So s.substring(2,5) returns 3 characters. This formula is faster than counting on the AP exam.

✍ Check for Understanding (8 Questions)

Your Score: 0 / 0
1. What does "computer".charAt(3) return?
2. What does "abcdef".substring(2,5) return?
3. How many iterations does this loop run?
String s = "hello";
for (int i=0; i
4. Which code correctly checks if the LAST character of String s is 'z'?
5. What does "racecar".indexOf("car") return?
6. Spot the error:
for (int i=0; i<=s.length(); i++)
  System.out.println(s.charAt(i));
7. Which loop correctly builds the String with every other character of s (indices 0,2,4,...)?
8. What does this code print when s = "Java"?
String r="";
for(int i=0;i  if(i%2==0) r+=s.charAt(i);
System.out.println(r);

❓ Frequently Asked Questions

How do you traverse a String in AP CSA?

Use a for loop: 'for (int i = 0; i < s.length(); i++)'. Access each character with s.charAt(i). The index runs from 0 to length()-1 inclusive. Using <= instead of < causes a StringIndexOutOfBoundsException.

What does charAt() do in Java?

charAt(i) returns the char at index i in the String. Strings are zero-indexed, so the first character is at index 0 and the last is at index length()-1.

What does substring(a, b) return?

substring(a, b) returns a new String containing characters from index a up to but NOT including index b. The length of the result is b - a.

How do I check if a character is a vowel in AP CSA?

Compare the char returned by charAt() to each vowel using ==: if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u'). Since charAt() returns a char primitive, == is the correct comparison (not .equals()).

How do I reverse a String in Java for AP CSA?

Initialize an empty String result = "". Use a for loop starting at index length()-1 and counting down to 0. In each iteration, append the current character: result += s.charAt(i). After the loop, result is the reversed string.

TC

Tanner Crow — AP CS Teacher & Tutor

11+ years teaching AP Computer Science at Blue Valley North High School (Overland Park, KS). Verified Wyzant tutor with 1,845+ hours, 451+ five-star reviews, and a 5.0 rating. His AP CSA students score 5s at more than double the national rate.

  • 54.5% of students score 5 on AP CSA (national avg: 25.5%)
  • 1,845+ verified tutoring hours • 5.0 rating
  • Free 1-on-1 tutoring inquiry: Wyzant Profile

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]