Unit 1 Cycle 2 Day 21: String Building with Conditionals

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

String Building with Conditionals

Section 1.10 — Strings: Methods

Key Concept

Building strings with conditionals involves constructing output character by character or segment by segment based on boolean conditions. A common AP exam pattern iterates through a string, appending characters to a result based on some test (e.g., if (Character.isUpperCase(ch))). Since strings are immutable, each concatenation creates a new String object. Trace these problems by maintaining a running value of the result string after each iteration or conditional branch.

Consider the following code segment.

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

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

Answer: (B) ECA

Index: A(0) B(1) C(2) D(3) E(4) F(5)

Loop goes backwards: i = 5, 4, 3, 2, 1, 0. Only adds when i % 2 == 0:

i=5: 5%2=1, skip.

i=4: 4%2=0, add "E". result = "E".

i=3: 3%2=1, skip.

i=2: 2%2=0, add "C". result = "EC".

i=1: 1%2=1, skip.

i=0: 0%2=0, add "A". result = "ECA".

Why Not the Others?

(A) These are the correct characters (even indices) but in forward order. The loop goes backward, so they append in reverse: E, C, A.

(C) Odd-indexed characters (B, D, F) are skipped by the i % 2 == 0 condition.

(D) Odd-indexed characters (F, D, B) in reverse. Wrong both in which characters are selected and the claim about order.

Common Mistake

Two things interact here: the backward loop AND the even-index filter. The characters at even indices are A(0), C(2), E(4), but since the loop runs backward (starting at 5), they are appended in reverse order: E, C, A.

AP Exam Tip

When a loop runs backward with a filter, trace every iteration. Write down whether each index passes the filter and what gets appended. Do not try to shortcut the reverse + filter combination.

Review this topic: Section 1.10 — Strings: Methods • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.