All 4 CS A units
AP Computer Science A · Unit 2 of 4

Selection and Iteration

25–35% of the exam4 lessons · 54 min53 terms

What this unit covers

The topics below follow the published CS A course framework for Unit 2. This unit is worth 25–35% of the exam, so budget your time against that rather than against how long the unit takes to teach.

Boolean logic & ifwhile & for loopsNested loopsAlgorithms & tracing

Lessons in this unit

Formulas in Unit 2

Truth of && and ||
a && b : true only if both true · a || b : true if either true
`!a` reverses a. Short-circuiting means the right operand may be skipped once the result is settled.
for loop header
for (init; test; update) { body }
init runs once; test is checked before each iteration; body then runs; update runs after the body; repeat until test is false.
Total inner executions (fixed bounds)
outer passes × inner passes = total inner-body runs
When the inner bound depends on the outer variable, add up the per-pass counts instead of multiplying.
Three-step swap
temp = a; a = b; b = temp;
The temporary variable preserves the first value so it is not lost when the second is copied in.

Every term in Unit 2

All 53 terms we publish for Selection and Iteration, with definitions. Reading them through is the fastest way to find the ones you cannot define — then drill those in cram mode until you can produce them without the prompt.

Short-circuit evaluation
&& stops if the left side is false; || stops if the left side is true. This is why `if (s != null && s.length() > 0)` is safe and the reverse order is not.
De Morgan's laws
!(a && b) is (!a || !b); !(a || b) is (!a && !b). The operator flips along with each term, and forgetting the flip is a standard trap.
if statement
Runs a block only when its boolean condition is true. Without braces, only the single next statement is controlled — a real source of logic errors.
if / else
Exactly one of the two blocks runs. The else attaches to the nearest unmatched if, which is what makes dangling-else questions work.
else if chain
Conditions are tested in order and the first true one runs; the rest are skipped. Order matters, and reordering an overlapping chain changes the output.
Nested if
An if inside another. Equivalent to && when there is no else, and not equivalent once an else is attached to the outer if.
Relational operators
==, !=, <, >, <=, >=. They compare primitives and produce a boolean. On objects, == compares references.
Logical AND
a && b is true only when both are true.
Logical OR
a || b is true when at least one is true.
Logical NOT
!a reverses a boolean. !(x > y) is x <= y — it includes equality.
Comparing doubles
Floating-point arithmetic makes exact equality unreliable, so compare with a tolerance — Math.abs(a − b) < 0.0001 — rather than ==.
Boolean expression as a value
A comparison is itself a boolean and can be returned or stored directly. `return x > y;` is better than an if/else returning true or false.
while loop
Tests the condition before each pass. If the condition is false at the start, the body never runs.
for loop
for (init; condition; update). Initialization runs once, the condition is tested before each pass, and the update runs after each pass.
Converting for to while
The initialization moves before the loop and the update goes at the end of the body. Equivalent unless the body contains a continue.
Loop counter scope
A variable declared in a for loop header exists only inside that loop. Referring to it afterward is a compile error.
Off-by-one error
Using < where <= was needed, or starting at 1 instead of 0. Test the first and last iterations by hand — that is where these hide.
Infinite loop
A loop whose condition never becomes false, usually because the variable it tests is never updated in the body.
Nested loops
A loop inside another. The inner loop completes fully for each single pass of the outer, so total iterations are the product.
Counting nested-loop iterations
Outer runs m times, inner runs n times per outer pass, so the body runs m × n times. When the inner bound depends on the outer counter, sum the sequence instead.
break
Exits the innermost loop immediately. Not used on the AP exam FRQs, but it can appear in code you must trace.
Loop over a String
for (int i = 0; i < s.length(); i++) with s.substring(i, i + 1) to get one character. Going to <= s.length() throws an exception.
Accumulator pattern
Initialize a running total before the loop, add to it inside, use it after. Initialize a sum to 0 and a product to 1.
Finding a maximum
Initialize to the first element, not to zero — initializing to zero returns the wrong answer for an all-negative array. Then compare each remaining element.
Counting matches in a loop
Initialize a counter to 0, increment inside the if, and read it after the loop ends. Reading it inside gives a partial count.
Flag variable
A boolean set before a loop and changed inside when a condition occurs, then tested afterward. Standard way to answer "did any element satisfy this?".
Tracing a loop
Draw a column per variable and a row per iteration, and fill the table. Slower than reading, and far more accurate — most lost marks here are from reading rather than tracing.
Sequential (linear) search
Check elements one at a time until the target is found or the collection ends. Works on unsorted data; worst case checks every element.
Binary search
Repeatedly halve a SORTED collection, discarding the half that cannot contain the target. Requires sorted data and roughly log₂n comparisons.
Binary search step count
Each comparison halves the remaining range, so n elements take about log₂n comparisons. A thousand elements take about ten.
Why binary search fails on unsorted data
It uses the middle element to decide which half to discard. Without ordering that decision is meaningless and the target can be thrown away.
Standard algorithm: sum and average
Accumulate a total in a loop, then divide by the count. Divide by a double, or cast, or integer division will truncate the average.
Standard algorithm: count occurrences
Loop through, increment a counter each time the condition holds. Return the counter after the loop.
Standard algorithm: determine if all elements meet a condition
Assume true, and set false the moment one element fails. Do not return true inside the loop — one passing element does not settle it.
Standard algorithm: determine if any element meets a condition
Assume false, and return true as soon as one matches. The mirror image of the "all" pattern, and mixing them up is a common error.
Standard algorithm: reverse
Build a new String or array from the end backward, or swap from both ends toward the middle, stopping at the midpoint. Looping the whole length while swapping undoes the work.
Standard algorithm: shift elements
Move each element to an adjacent index. Going forward overwrites data unless you loop in the opposite direction from the shift.
Recursion (trace only in the 2025 CED)
A method that calls itself. On the current exam you trace given recursive code and state its return value; you are not asked to write a recursive method.
Base case
The condition under which a recursive method returns without calling itself. Without it the calls never stop and the program throws StackOverflowError.
Tracing a recursive call
Write each call on its own line, indented, and resolve the innermost one first — then substitute results back outward. Trying to hold it in your head is where the marks go.
Recursive method with an accumulating return
Something like `return n + sum(n − 1);` builds its answer on the way back out, not on the way in. Reach the base case first, then add upward.
StackOverflowError
Thrown when recursion goes too deep, almost always because the base case is wrong or never reached.
do-while loop
Tests the condition after the body, so the body always runs at least once. Not part of the AP subset, but it can appear in code you read.
Compound boolean in a loop condition
while (i < n && arr[i] != target) relies on short-circuiting to avoid indexing out of bounds. Reversing the operands throws an exception on the last pass.
Common cause of an unexpected zero
Integer division inside a loop — sum / count where both are int. Cast one operand to double before dividing.
Tracing output with print vs println
Consecutive print calls put everything on one line. Questions that look like they have several answers often differ only in line breaks.
Loop invariant thinking
Ask what is true about the accumulator at the start of each pass. It makes off-by-one errors visible without running the code.
Conditional (ternary) operator
condition ? valueIfTrue : valueIfFalse. Not in the AP Java subset for writing, but readable code may use it.
Order of evaluation in a condition
Java evaluates left to right and stops as soon as the result is determined. Side effects in the right operand may never happen.
Empty loop body danger
A stray semicolon after a for or while header makes the body empty, so the loop runs to completion doing nothing. Compiles cleanly and produces silent wrong output.
Testing loop boundaries
Run the code mentally with an empty collection, one element, and the maximum index. Nearly all loop bugs appear in one of those three.
Choosing while over for
Use for when the number of iterations is known before the loop starts, while when it depends on something discovered inside.
Nested loop with a dependent inner bound
When the inner loop runs `i` times on outer pass i, total iterations are 1 + 2 + ... + n = n(n + 1) / 2, not n².

What examiners penalize here

Practice CS A

Our practice bank is drawn from across the whole course rather than filtered to one unit, which is closer to how the exam asks anyway — it will not tell you which unit a question is testing.

Questions about this unit

How much of the AP Computer Science A exam is Unit 2?

Unit 2, Selection and Iteration, is worth 25–35% of the CS A multiple-choice section according to the published course framework. Across all 4 units that makes it one of the heaviest units on the exam, and worth front-loading.

What topics are covered in CS A Unit 2?

Selection and Iteration covers Boolean logic & if, while & for loops, Nested loops and Algorithms & tracing. We publish 53 terms with definitions for this unit, all of them on this page.

How should I study CS A Unit 2?

Read the 4 lessons below first — about 55 minutes — then drill the 53 terms in cram mode until you can produce each definition from memory rather than just recognize it. Recognition is what makes a unit feel finished when it is not. Finish with practice questions and read the explanation for every one you get right by elimination as well as the ones you miss.

All 4 units of AP Computer Science A

  1. Unit 1 · Using Objects and Methods
  2. Unit 2 · Selection and Iteration
  3. Unit 3 · Class Creation
  4. Unit 4 · Data Collections

Unit names, topics and exam weights follow the published College Board course framework for AP Computer Science A. AP® is a trademark registered by the College Board, which does not endorse this site.