AP Computer Science A Unit 2 ReviewSelection and Iteration

Verified for the 2027 examCompiled by AP educators
Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly→ and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc

AP Computer Science A Unit 2, Selection and Iteration, covers iteration, selection, and decision-making logic across 12 topics, making up 25-35% of the AP exam, with boolean expressions as the central mechanism tying it all together. In AP CSA, that means writing `if` statements, nested `if` statements, `while` loops, and `for` loops in Java. You'll also work with boolean expressions, compound conditions, and string algorithms, plus get an intro to run-time analysis.

unit 2 review

AP Computer Science A Unit 2 is where your programs stop running in a straight line and start making choices and repeating work. The single biggest idea is control flow, which means using Boolean expressions to drive if statements (selection) and while and for loops (iteration) so a program can respond to conditions and process data many times. This content makes up 25-35% of the AP exam, the heaviest weight in the course, because nearly every line of AP Java you write from here on lives inside a condition or a loop.

What this unit covers

Boolean logic, the decision engine

  • Every decision in Java boils down to an expression that evaluates to true or false. Relational operators (==, !=, <, >, <=, >=) compare values and produce a Boolean result.
  • With primitives, == compares actual values. With objects, == compares references (whether two variables point to the same object in memory). That is why strings and other objects use .equals() instead, since classes define their own criteria for what counts as equivalent.
  • Logical operators combine conditions. !a flips a value, a && b is true only when both are true, and a || b is true when at least one is true. Precedence runs ! first, then &&, then ||.
  • Two Boolean expressions are equivalent if they produce the same value in every case, and a truth table proves it. De Morgan's law gives you the standard rewrites. !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Notice how the operator flips when the ! distributes.
  • You can compare a reference with null using == or != to check whether a variable actually points to an object before you call methods on it.

Selection: if, if-else, and multiway branching

  • An if statement runs a block of code only when its Boolean expression is true. One-way selection skips the block entirely when the condition is false.
  • Two-way selection (if-else) guarantees exactly one of two paths runs. Multiway selection (if-else-if) checks a series of conditions in order and runs at most one block, the first one whose condition is true.
  • Nested if statements put a decision inside another decision. The inner condition is only evaluated when the outer condition is true, so structure and ordering change behavior. Separate if statements can all fire; an if-else-if chain fires at most once.

Iteration: while loops, for loops, and nesting

  • A while loop checks its condition before every iteration, including the first. If the condition starts false, the body never runs at all. If the condition never becomes false, you get an infinite loop.
  • A for loop packs three parts into its header. The initialization runs once and creates the loop control variable, the Boolean expression is checked before each pass, and the update runs after each pass. It is a while loop with the bookkeeping built in.
  • Off-by-one errors happen when a loop runs one time too many or one time too few, usually from mixing up < and <= or starting the counter at the wrong value. Trace the first and last iterations to catch them.
  • Nested iteration puts a loop inside a loop. The inner loop must finish all of its iterations before the outer loop moves to its next iteration. A 3-by-4 nested pair runs the inner body 12 times.

Standard algorithms you write from scratch

  • Divisibility checks use the modulus operator. n % d == 0 means d divides n evenly, which is how you test for even, odd, or multiples.
  • Digit extraction peels apart an integer with n % 10 (grab the last digit) and n / 10 (drop the last digit), looped until n reaches 0.
  • Accumulator patterns compute a sum or average, count how many values meet a condition (frequency), or track a running minimum or maximum as a loop processes values.
  • String algorithms loop through a string with charAt or substring to check whether substrings have a property, count substrings that meet a criterion, or build a reversed copy one character at a time.

Informal run-time analysis

  • A statement execution count is the number of times one specific statement runs. You figure it out by tracing the loop, not by memorizing formulas.
  • For nested loops, multiply. If the outer loop runs n times and the inner loop runs m times per outer pass, the inner body executes n * m times.
  • Comparing execution counts lets you say which of two loop structures does less work, which is the informal version of efficiency analysis.

Unit 2, Using Objects in AP Computer Science A at a glance

TopicCore ideaWatch out for
Algorithms with selection and repetitionSequencing, selection, and repetition are the three building blocks of every algorithmThe order you combine them changes the outcome
Boolean expressionsRelational operators produce true or false== on objects compares references, not contents
if / if-else / if-else-ifOne-way, two-way, and multiway branchingOnly the first true branch of a chain runs
Nested if statementsDecisions inside decisions; inner runs only if outer is trueMisreading which else pairs with which if
Compound Booleans and De Morgan's law!, &&, `
while loopsCondition checked before every iterationBody may run zero times; forgetting the update causes infinite loops
for loopsInitialization, condition, update packed in the headerUpdate runs after each pass, before the next condition check
Nested iterationInner loop completes fully each time the outer loop runs onceTotal inner-body executions multiply
Selection and iteration algorithmsDivisibility, digit extraction, sum, average, min, max, frequencyInitialize accumulators before the loop, not inside it
String algorithmsLoop over characters to test, count, or reversesubstring(i, i + 1) grabs one character as a String
Informal run-time analysisCount how many times a statement executesOff-by-one in your trace skews the whole count

Why Unit 2, Using Objects in AP Computer Science A matters in AP CSA

This unit carries the course's central skill set, which is developing code to implement an algorithm and determining what code produces when it runs. Selection and iteration are not one chapter you finish; they are the grammar of everything that follows.

  • At 25-35% of the exam, this is the single heaviest unit, and its patterns appear inside questions tagged to every other unit.
  • The accumulator patterns here (sum, count, min, max) are exactly what you reuse when traversing arrays and ArrayLists later, just with a loop over indexes instead of digits or characters.
  • Tracing code and counting executions builds the careful, line-by-line reading you need for every multiple-choice "what does this print" question and every free-response rubric point.

How this unit connects across the course

  • Builds directly on variables, expressions, and String methods like substring and charAt from Using Objects and Methods (Unit 1). The reference vs. primitive distinction from Unit 1 explains why == behaves differently on objects.
  • When you write your own classes in Class Creation (Unit 3), your methods are mostly conditionals and loops. An equals method, for example, is a Boolean expression comparing attributes.
  • Data Collections (Unit 4) is this unit applied to arrays, ArrayLists, and 2D arrays. Linear search is a loop with an if inside; selection sort and insertion sort are nested iteration; traversing a 2D array is the row-by-column nested loop pattern from Topic 2.11.

Key syntax and algorithms

  • if (condition) { } else if (condition) { } else { } branches execution; at most one block in the chain runs.
  • while (condition) { } repeats as long as the condition is true, checking before each pass (zero or more executions).
  • for (int i = 0; i < n; i++) { } runs the body exactly n times; initialization once, condition before each pass, update after each pass.
  • a && b, a || b, !a combine Booleans; precedence is !, then &&, then ||.
  • De Morgan's law: !(a && b) is !a || !b and !(a || b) is !a && !b.
  • obj1.equals(obj2) compares object contents; obj1 == obj2 compares references; ref == null checks for a missing object.
  • Divisibility test: n % d == 0 is true when d evenly divides n.
  • Digit loop: repeat digit = n % 10; n = n / 10; until n == 0 to process each digit.
  • Accumulators: initialize sum = 0, count = 0, or max = first value before the loop, then update inside it; compute average as (double) sum / count to avoid integer division.
  • String reversal: build rev = str.substring(i, i + 1) + rev; (or loop backward and append) across all indexes.
  • Execution counting: a loop from i = 1 to i <= n runs n times; nested loops multiply their counts.

Unit 2, Using Objects in AP Computer Science A on the AP exam

This unit is worth 25-35% of the exam, more than any other. On the multiple-choice section, expect to determine the result of code segments. You'll trace loops to find what prints, count how many times a statement executes, identify which Boolean expression is equivalent to a given one (De Morgan's law shows up constantly), and spot off-by-one and infinite-loop bugs. Some questions hand you several code segments and ask which ones produce identical output.

On the free-response section, selection and iteration are the muscle behind nearly every rubric point. Methods FRQs ask you to write loops with conditions inside them, including accumulator patterns like counting matches, summing values, or finding a max, and string-processing FRQs require you to traverse a string with substring or charAt and apply criteria to each piece. Even when an FRQ is officially about classes or arrays, the points you earn usually come from a correctly bounded loop and a correctly written condition.

Essential questions

  • How do selection and repetition turn a fixed list of instructions into a program that adapts to its input?
  • When do two different-looking Boolean expressions or code segments actually behave identically in every case?
  • How do you choose between a while loop and a for loop, and how do you guarantee a loop runs the right number of times?
  • How can you measure how much work code does without running it?

Key terms to know

  • Selection: Choosing which code executes based on whether a Boolean expression is true or false.
  • Iteration: Repeating a code segment zero or more times while a controlling condition stays true.
  • Boolean expression: Any expression that evaluates to true or false, built from relational and logical operators.
  • Relational operators: ==, !=, <, >, <=, >=, which compare values and produce a Boolean.
  • Logical operators: !, &&, and ||, which negate and combine Boolean expressions.
  • Truth table: A chart of all input combinations used to prove two Boolean expressions are equivalent.
  • De Morgan's law: The rule for distributing ! across && and ||, flipping the operator in the process.
  • Multiway selection: An if-else-if chain where at most one branch executes, the first true one.
  • Loop control variable: The variable initialized, tested, and updated by a for loop header.
  • Infinite loop: A loop whose condition never becomes false, so it never terminates.
  • Off-by-one error: A loop that runs exactly one time too many or too few, often from a < vs. <= slip.
  • Nested iteration: A loop inside a loop, where the inner loop fully completes on each outer iteration.
  • Statement execution count: The number of times a particular statement runs, found by tracing the loops around it.
  • Accumulator: A variable (sum, count, max, min) initialized before a loop and updated each iteration to build a result.

Common mix-ups

  • == vs. .equals() on objects. == asks "same object in memory?" while .equals() asks "equivalent according to the class?" Two different String objects with identical characters are .equals() but may not be ==.
  • A chain of separate if statements vs. one if-else-if chain. Separate ifs can all execute on the same pass; a chain executes at most one branch. Swapping one for the other changes the output.
  • while loop condition placement. The condition is checked before every iteration, so a loop can legitimately run zero times. It is not "run once, then check."
  • Distributing ! without flipping the operator. !(a && b) is not !a && !b. De Morgan's law requires && to become || (and vice versa) when the negation moves inside.