Unit 2 Cycle 1 Day 17: String Traversal with charAt

Unit 2 Foundation (Cycle 1) Day 17 of 28 Foundation

String Traversal with charAt

Section 2.11 — String Traversal

Key Concept

String traversal uses a for loop with charAt(index) to access each character. The standard pattern is for (int i = 0; i < str.length(); i++) with str.charAt(i) inside the body. Remember that charAt() returns a char, not a String. To compare a char to a letter, use single quotes: ch == 'a'. To compare to a String, use str.substring(i, i + 1).equals("a"). The AP exam frequently tests both approaches and expects you to know the difference.

Consider the following code segment.

String word = "BANANA"; int count = 0; for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == 'A') { count++; } } System.out.println(count);

What is printed as a result of executing the code segment?

Answer: (B) 3

B(0) A(1) N(2) A(3) N(4) A(5). Characters equal to 'A' are at indices 1, 3, 5. Count = 3.

Why Not the Others?

(A) There are 3 A's in "BANANA", not 2. Check all 6 indices.

(C) 1 would mean only one A was found, but there are three.

(D) 6 is the total number of characters, not the count of A's.

Common Mistake

charAt(i) returns a char, which is compared with == (not .equals()). For single characters, == is correct because char is a primitive type.

AP Exam Tip

Use == to compare char values (primitives) and .equals() to compare String values (objects). charAt() returns a char.

Review this topic: Section 2.11 — String Traversal • 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.