Unit 2 Cycle 1 Day 18: Building a String with Traversal

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

Building a String with Traversal

Section 2.11 — String Traversal

Key Concept

Building a new string from a traversal is a common AP exam pattern. Start with an empty string String result = "", iterate through the source string, and conditionally append characters using concatenation. For example, removing all vowels: check each character and append it to result only if it is not a vowel. Since String is immutable, each concatenation creates a new object, but this is acceptable for AP exam purposes. Always trace the result string value after each iteration.

Consider the following code segment.

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

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

Answer: (B) olleH

The loop goes from index 4 down to 0, appending each character: o, l, l, e, H. Result = "olleH". This reverses the string.

Why Not the Others?

(A) The loop traverses backward, so the string is reversed, not copied as-is.

(C) This is missing the first character appended ("o" at index 4).

(D) The characters append in reverse index order: 4,3,2,1,0 giving o,l,l,e,H.

Common Mistake

A backward loop (i = length-1 down to 0) combined with appending builds the string in reverse. This is a standard string reversal algorithm.

AP Exam Tip

The AP exam commonly asks you to trace string building with loops. Write out each iteration's append operation. The order of the loop directly determines the order of characters.

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.