Skip to content
  • Open the math solver
  • Ask the AI tutor
  • Find an AP course
  • Create a quiz
  • Open the calculator
  • Graphing Calculator
  • Browse all calculators
  • Read math guides
↑ ↓Enter to open · Esc to close
Solve a problem
UnofficialAP Computer Science AUnit 2 of 4

AP Computer Science A Unit 2: Selection and Iteration

Boolean expressions, if statements, while and for loops and tracing.

Unit overview

Selection and iteration control the flow of a program. Boolean expressions combine relational operators with &&, || and !, and Java evaluates them with short-circuit logic: if the left side of && is false, the right side is never evaluated. De Morgan's laws let you rewrite negated conditions, so !(a && b) is equivalent to !a || !b.

if, else if and else statements choose between branches, and only the first true branch runs. while loops repeat while a condition is true; for loops package initialisation, condition and update in one header. Tracing a loop by hand, writing down each variable after each iteration, is the most reliable way to answer output questions and to find off-by-one errors.

Key topics

Boolean expressions
Relational and logical operators, short-circuit evaluation and De Morgan's laws.
if statements
Nested and chained conditionals; only one branch of an if-else chain runs.
while and for loops
Loop conditions, updates and how many times the body runs.
Loop tracing
Tables of variable values to predict output and spot off-by-one errors.

Worked example

How many times does the body of for (int i = 3; i < 20; i += 4) run?

  1. i takes the values 3, 7, 11, 15 and 19.
  2. The next value, 23, fails i < 20, so the body runs 5 times.

Answer: 55 times

Common mistakes

  • Using = instead of == in a condition, or comparing String objects with == instead of equals.
  • Off-by-one errors from < versus <= in loop conditions.
  • Forgetting to update the loop variable in a while loop, producing an infinite loop.

Exam tips

  • Trace with a table: one column per variable, one row per iteration.
  • Check edge cases such as an empty input or a loop that runs zero times.

See the AP Computer Science A exam format and every unit on the course page.