Unit 2 Cycle 2 Day 21: String Processing with Conditional Replace

Unit 2 Advanced (Cycle 2) Day 21 of 28 Advanced

String Processing with Conditional Replace

Section 2.11 — String Traversal

Key Concept

String processing with conditional replacement builds a new string by iterating through the original and replacing certain characters or substrings. The pattern is: for (int i = 0; i < str.length(); i++) { if (condition) result += replacement; else result += str.substring(i, i+1); }. The AP exam tests variations where the replacement is a different character, the condition involves checking neighboring characters, or the replacement is a different length than the original, which changes the indices if you are not building a new string.

Consider the following code segment.

String s = "Java is fun"; String result = ""; for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); if (ch.equals(" ")) { result += "_"; } else { result += ch; } } System.out.println(result);

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

Answer: (A) Java_is_fun

The code replaces every space with an underscore. J-a-v-a: kept. Space: replaced with _. i-s: kept. Space: replaced with _. f-u-n: kept. Result: "Java_is_fun".

Why Not the Others?

(B) The original string has spaces, but the code replaces them with underscores.

(C) Both spaces are replaced, not just the first one.

(D) Both spaces are replaced. The loop processes every character.

Common Mistake

String traversal with character replacement builds a new string character by character. Since Strings are immutable in Java, you must build a new String (you cannot modify the original).

AP Exam Tip

String replacement via traversal is a common AP exam pattern. Build a new string, checking each character and appending the original or replacement.

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.