Unit 2 Cycle 1 Day 17: String Traversal with charAt
Share
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.
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.