Skip to main content

AP Computer Science A Unit 2 Review: Selection and Iteration

  • 25–35% of AP multiple choice
  • 12 topics
  • AP exam review verified for 2027

Unit 2 teaches you how to make programs choose between paths using Boolean expressions and if statements, and how to repeat code using while and for loops. You also learn standard algorithms, string processing, nested loops, and how to count how many times statements execute.

Fiveable's AP Computer Science A Unit 2 review covers 13 topics, with guided practice questions for the unit.

start with 2.1start unit practiceReview with a tutorFree, 24/7, real people, from UPchieve

AP Computer Science A unit 2 topics

2.2

Boolean Expressions

Covers relational operators ==, !=, <, >, <=, >= and the rule that primitive comparisons check values while reference comparisons check memory addresses.

open guide
2.3

if Statements

Introduces one-way (if) and two-way (if-else) selection. The body of an if runs only when its Boolean expression is true; the else body runs when it is false.

open guide
2.4

Nested if Statements

Covers nested if statements and multiway if-else-if chains. The inner condition is only evaluated when the outer condition is true; the first true branch in a chain runs and the rest are skipped.

open guide
2.7

while Loops

A while loop checks its condition before every iteration. It can run zero times, and it causes an infinite loop if the condition never becomes false. Off-by-one errors are common.

open guide
2.8

for Loops

A for loop header contains initialization, Boolean condition, and update. Initialization runs once; the condition is checked before each iteration; the update runs after each body execution.

open guide
2.11

Nested Iteration

The inner loop completes all its iterations each time the outer loop advances once. Total execution count is the product of bounds for independent loops or triangular for dependent bounds.

open guide
2.12

Informal Run-Time Analysis

Count how many times a statement executes by tracing loop bounds. Single loops are linear; independent nested loops are quadratic; triangular nested loops produce n(n-1)/2 executions.

open guide
2.6

2.6 Equivalent Boolean Expressions

Review AP Computer Science A Topic 2.6, including equivalent Boolean expressions, comparing Boolean expressions, truth tables, De Morgan's law, !(a && b), !(a || b), ==, !=, null checks, and .equals().

open guide

Practice AP Computer Science A unit 2 questions

Try AP-style questions on unit 2, then use the review notes below for anything you miss.

AP Computer Science A unit 2 practice MCQs

open all practice
MCQ

AP-style practice question

Question

Consider the following code segment:

</>Java
int runs = 0;
int n = /* missing initialization */;
for (int i = 1; i < n; i *= 2) {
    for (int j = 0; j < i; j++) {
        runs++;
    }
}

Which of the following replacements for /* missing initialization */ will cause the runs++; statement to execute exactly 15 times?

int n = 18;

int n = 34;

int n = 66;

int n = 10;

MCQ

AP-style practice question

Question

Consider the following code segment.

</>Java
String str1 = /* missing initialization */;
String str2 = /* missing initialization */;
boolean diff = (str1 != str2) == str1.equals(str2);

Which of the following initial conditions will cause diff to evaluate to true?

str1 and str2 reference the same object with identical text.

str1 and str2 reference distinct objects with identical text.

str1 and str2 reference distinct objects with different text.

str1 and str2 reference distinct objects of different lengths.

AP Computer Science A unit 2 FRQs

open all FRQs
FRQ

Cyclic direction-state simulation and String rotation

1. This question involves the DirectionDisplay class. You will implement two methods using the specifications and examples below. The helper method is provided; its implementation is not shown.

</>Java
public class DirectionDisplay
{
  /** Consumes and returns the next command, which is exactly "L", "R" or "S".
   * There are enough commands for every requested call. */
  public String readToken() { /* implementation not shown */ }
  /** Implements the behavior and preconditions in part (a). */
  public int finalDirection(int moves)
  { /* to be implemented in part (a) */ }
  /** Implements the behavior and preconditions in part (b). */
  public String rotateLabel(String label, int positions)
  { /* to be implemented in part (b) */ }
}
a.

Write finalDirection. Begin facing direction 0. Directions are numbered 0, 1, 2 and 3 in clockwise order. Consume exactly moves commands by calling readToken once for each command. An "R" command turns one direction clockwise; an "L" command turns one direction counterclockwise; an "S" command leaves the direction unchanged. Turning past 3 clockwise reaches 0; turning past 0 counterclockwise reaches 3. Return the final direction. Assume moves >= 0. Each call begins at direction 0 independently of earlier calls. You must use readToken appropriately.

Examples

Each call is independent.
CallSuccessive commandsReturn value
finalDirection(5)R, R, L, S, R2
finalDirection(3)L, S, L2
finalDirection(0)No helper calls0
The first sequence produces directions 1, 2, 1, 1 and 2. The second produces 3, 3 and 2. No command is consumed for moves equal to 0.
Complete finalDirection.
/** Implements the behavior and preconditions specified in this part. */
public int finalDirection(int moves)
b.

Write rotateLabel. Rotate label to the left by positions characters and return the result. Characters moved past the beginning reappear at the end in the same order. Every full rotation of label.length() positions leaves the label unchanged. Assume label is nonempty and not null, and positions >= 0. Do not change the letter case.

Examples

Each call is independent.
Method callReturn value
rotateLabel("north", 2)"rthno"
rotateLabel("ABCD", 4)"ABCD"
rotateLabel("level", 7)"velle"
rotateLabel("x", 9)"x"
For level, seven positions are equivalent to two positions because the string length is five. Moving the first two characters, le, to the end gives velle.
Complete rotateLabel.
/** Implements the behavior and preconditions specified in this part. */
public String rotateLabel(String label, int positions)

AP Computer Science A unit 2 practice test

A timed, AP-style test built only from unit 2 questions — multiple choice plus free response, scored with AI feedback. Use the standard format or build your own.

Take the unit 2 practice test

Unit 2 review notes

2.1

Algorithms with selection and repetition

An algorithm is a step-by-step process for solving a problem. The three building blocks are sequencing (executing statements in order), selection (branching based on a true or false condition), and repetition (looping until a goal is reached). You can represent algorithms in plain language or with flowcharts before writing Java code. The order in which these building blocks appear changes the outcome.

  • Sequencing: Statements execute in the order they are written; changing the order changes the result.
  • Selection: A true or false decision determines which path the algorithm takes at a branch point.
  • Repetition: A process repeats until a desired outcome is reached, modeled with loops in Java.
  • Flowchart decision diamond: A diamond shape in a diagram represents a true or false question that splits the algorithm into two paths.

Describe a real-world task, such as sorting mail, using all three building blocks. Identify where the selection and repetition occur.

Building blockJava constructWhen to use
SequencingStatements in orderSteps that must happen in a fixed sequence
Selectionif, if-else, if-else-ifDifferent actions needed for different conditions
Repetitionwhile, forSame action needed multiple times until a goal is met
2.2

Boolean expressions and relational operators

A Boolean expression evaluates to either true or false. Relational operators compare two values and produce a Boolean result. With primitive types, == and != compare actual values. With reference types, == and != compare object references, not content. To compare String content, use .equals().

  • Relational operator: ==, !=, <, >, <=, >= compare two values and return a Boolean result.
  • Primitive comparison: int, double, and char values compared with == check the actual stored value.
  • Reference comparison: Using == on two object variables checks whether they point to the same object in memory, not whether their contents are equal.
  • Equality comparison: For objects, use .equals() to test content equality; use == only to test whether two variables reference the exact same object.

Write a Boolean expression that is true when an int variable score is between 70 and 89 inclusive. Then explain why you cannot use == to compare two String variables for equal content.

Operand typeOperatorWhat is compared
int, double, char==, !=, <, >, <=, >=Actual primitive values
Object references==, !=Memory addresses (same object?)
String content.equals()Character-by-character content
2.3

if statements and nested if statements

An if statement changes sequential flow by running a block only when its Boolean expression is true. An if-else adds a second block for when the condition is false. Nested if statements place one decision inside another; the inner condition is only evaluated when the outer condition is true. A multiway if-else-if chain checks conditions in order and executes the first true branch, then skips all remaining branches. If no condition is true and a trailing else exists, that else block runs.

  • One-way selection: An if statement runs its body only when the condition is true; nothing happens when it is false.
  • Two-way selection: An if-else runs one block when the condition is true and the other when it is false; exactly one block always runs.
  • Nested if: An if or if-else placed inside another if block; the inner condition is only reached when the outer condition is true.
  • Multiway selection: An if-else-if chain evaluates conditions top to bottom and executes only the first true branch.
  • Trailing else: An else at the end of an if-else-if chain that runs when no earlier condition was true.

Trace this logic: a variable grade is 85. An if-else-if checks grade >= 90 first, then grade >= 80, then grade >= 70, with a trailing else. Which block runs and why?

FormBlocks that can runWhen to use
if0 or 1Optional action under one condition
if-elseExactly 1 of 2Two mutually exclusive outcomes
if-else-if0 or 1 of manyMultiple mutually exclusive categories
Nested ifDepends on outerLayered conditions where inner depends on outer
2.5

Compound Boolean expressions and equivalence

Logical operators combine Boolean expressions. ! (not) negates a value. && (and) is true only when both operands are true. || (or) is true when at least one operand is true. Precedence order is !, then &&, then ||. Short-circuit evaluation means Java stops evaluating as soon as the result is determined: for &&, if the left side is false, the right side is skipped; for ||, if the left side is true, the right side is skipped. Two Boolean expressions are equivalent if they produce the same result for every possible input. De Morgan's law gives two key equivalences: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Truth tables prove equivalence by listing all input combinations.

  • Short-circuit evaluation: Java stops evaluating && when the left operand is false, and stops evaluating || when the left operand is true, so the right operand may never be checked.
  • De Morgan's law: !(a && b) is equivalent to !a || !b; !(a || b) is equivalent to !a && !b. Use these to rewrite negated compound conditions.
  • Truth tables: A table listing all true/false combinations for variables to verify that two Boolean expressions always produce the same output.
  • Operator precedence: ! is evaluated first, then &&, then ||. Use parentheses to override this order when needed.
  • Null comparison: Use obj == null or obj != null to check whether a reference variable holds an object before calling methods on it.

Apply De Morgan's law to rewrite !(x > 5 && y < 10) without the outer negation. Then build a truth table for a && !b to verify your understanding.

OperatorTrue whenShort-circuits when
!Operand is falseAlways (single operand)
&&Both operands are trueLeft operand is false
||At least one operand is trueLeft operand is true
2.7

while loops

A while loop evaluates its Boolean condition before every iteration, including the first. If the condition is false initially, the loop body never runs. The loop continues as long as the condition is true. If the condition never becomes false, the result is an infinite loop. Off-by-one errors occur when the loop runs one time too many or too few, usually because the condition uses < instead of <= or vice versa. A loop control variable must be initialized before the loop and updated inside the loop body.

  • Pretest loop: A while loop checks its condition before the body runs, so it can execute zero times if the condition starts false.
  • Infinite loop: Occurs when the loop condition always evaluates to true because the loop variable is never updated or the update does not move toward termination.
  • Off by one error: The loop runs one iteration too many or too few, often caused by using < vs <= or initializing the counter incorrectly.
  • Accumulator pattern: Initialize a variable before the loop, then update it inside the loop body each iteration to build a running total or count.

Write a while loop that sums integers from 1 to 10. Identify the initialization, condition, body, and update. Then change the condition to cause an off-by-one error and explain what goes wrong.

2.8

for loops

A for loop header has three parts: initialization (runs once before the first condition check), Boolean expression (checked before every iteration), and update (runs after every loop body execution). The variable declared in the initialization is the loop control variable. A for loop can always be rewritten as an equivalent while loop and vice versa. For loops are preferred when the number of iterations is known in advance.

  • Loop control variable: The variable declared in the for loop initialization, used to count iterations and control when the loop ends.
  • Initialization: Runs exactly once before the first condition check; sets the starting value of the loop control variable.
  • Update: Runs after every execution of the loop body and before the next condition check; typically increments or decrements the loop control variable.
  • for-to-while conversion: Any for loop can be rewritten as a while loop by moving initialization before the loop and the update to the end of the loop body.

Trace a for loop with header for(int i = 1; i <= 5; i++) that prints i * i. List the value of i and the output for each iteration. Then rewrite it as an equivalent while loop.

Loop typeCondition checkedBest use case
whileBefore each iteration (pretest)Unknown number of iterations; event-driven termination
forBefore each iteration (pretest)Known number of iterations; index-based traversal
2.9

Implementing selection and iteration algorithms

Standard algorithms combine if statements and loops to solve common problems without using arrays. The modulus operator % finds remainders and tests divisibility. Digit extraction uses % 10 to get the last digit and integer division by 10 to remove it, repeating in a loop. Frequency counting uses a conditional increment inside a loop. Min and max tracking initializes a variable to the first value and updates it when a new value is smaller or larger. Sum and average use an accumulator variable updated each iteration.

  • Digit extraction: Use n % 10 to get the ones digit and n / 10 to shift right; repeat in a while loop until n equals 0.
  • Accumulator variable: Initialized before the loop and updated inside it to compute a running sum, count, or other aggregate value.
  • Maximum value algorithm: Initialize a max variable, then compare each new value to max inside a loop and update max when a larger value is found.
  • Count variable: Incremented inside a loop only when a condition is true, used to count how many values meet a specific criterion.

Write a loop that counts how many digits in a positive integer are greater than 5. Identify which standard algorithm patterns you are combining.

AlgorithmKey operationPattern
Divisibility checkn % d == 0Single Boolean expression
Digit extractionn % 10, n / 10while loop, shrink n each pass
Frequency countif condition, count++Accumulator with conditional increment
Min/max trackingif new > max, updateAccumulator with conditional update
Sum and averagesum += valueAccumulator, divide by count at end
2.10

String algorithms

String algorithms use loops with String methods to examine text one character or substring at a time. The three standard goals are checking whether substrings have a property, counting substrings that meet criteria, and building a reversed string. Key methods are charAt(i) to get a character at index i, substring(start, end) to extract a portion, length() to get the string length, and indexOf() to search. Loop bounds matter: valid indices run from 0 to length() - 1. Strings are immutable, so building a new string requires concatenation or a new variable.

  • charAt: Returns the char at a given index; valid indices are 0 through length() - 1.
  • substring: substring(start, end) returns characters from index start up to but not including index end.
  • String immutability: Strings cannot be changed in place; operations like reversal require building a new String variable.
  • Overlapping occurrences: When counting substring matches, decide whether overlapping instances count separately; adjust the loop index accordingly.

Write a loop that builds the reverse of a String s by concatenating characters from the last index to index 0. Identify the loop bounds and explain why length() - 1 is the correct starting index.

2.11

Nested iteration

Nested iteration places one loop inside another. The inner loop completes all of its iterations every time the outer loop runs once. To trace nested loops, track both loop variables together. The total number of inner loop body executions is the product of the outer and inner iteration counts for independent bounds. When inner bounds depend on the outer variable, the count is triangular.

  • Inner loop reset: Each time the outer loop advances one iteration, the inner loop variable resets to its initial value and runs through all its iterations again.
  • Dependent inner bounds: When the inner loop runs from 0 to i (the outer variable), the total iterations form a triangular pattern: 0 + 1 + 2 + ... + (n-1) = n(n-1)/2.
  • Cartesian product: Independent nested loops with bounds m and n produce m * n total inner loop executions, one for each (i, j) pair.

Trace a nested loop where the outer runs i from 0 to 2 and the inner runs j from 0 to i. List every (i, j) pair that executes and count the total inner loop body executions.

Loop structureTotal inner executionsExample
Independent bounds (m outer, n inner)m * nfor i 0..2, for j 0..3: 12 executions
Dependent bounds (inner 0 to i)n(n-1)/2for i 0..4, for j 0..i: 10 executions
2.12

Informal run-time analysis

A statement execution count is the number of times a specific statement runs. You find it by tracing the loop structure and counting iterations. For a single loop running n times, a statement in the body executes n times. For independent nested loops with bounds m and n, the inner body executes m * n times. For a triangular nested loop, the inner body executes approximately n squared divided by 2 times. Informal run-time analysis compares two iterative segments by comparing their execution counts as input size grows, without requiring formal Big O notation.

  • Statement execution count: The exact number of times a statement runs, determined by tracing loop bounds and conditions.
  • Linear iteration: A single loop with bound n executes its body n times; execution count grows proportionally with n.
  • Quadratic iteration: Independent nested loops with bound n each produce n * n inner body executions; count grows with the square of n.
  • Triangular loop count: A nested loop where the inner bound depends on the outer variable produces approximately n(n-1)/2 inner executions.

Given a nested loop where the outer runs from 1 to 4 and the inner runs from 1 to 3, calculate the exact execution count of a statement in the inner body. Then describe how the count changes if both bounds double.

Loop structureExecution count formulaGrowth type
Single loop, bound nnLinear
Independent nested loops, bound n eachn * nQuadratic
Triangular nested loop, bound nn(n-1)/2Quadratic (slower constant)

Key terms

TermDefinition
relational operatorAn operator that compares two values and returns a Boolean result. In AP CSA the relational operators are ==, !=, <, >, <=, and >=.
== (equality operator)Compares two values for equality. With primitives it compares actual values; with reference types it compares object references, not content.
short-circuit evaluationJava stops evaluating && when the left operand is false, and stops evaluating || when the left operand is true, so the right operand may never be checked.
De Morgan's law!(a && b) is equivalent to !a || !b, and !(a || b) is equivalent to !a && !b. Use these rules to rewrite negated compound conditions.
truth tablesA table listing all true/false input combinations and their output for a Boolean expression, used to prove two expressions are equivalent.
off by one errorA loop runs one iteration too many or too few because the condition uses < instead of <= or the counter is initialized incorrectly.
accumulator patternA variable is initialized before a loop and updated inside the loop body each iteration to compute a running sum, count, or other aggregate.
accumulator variableThe variable used in the accumulator pattern; initialized once and incremented or updated repeatedly during iteration.
digit extractionA standard algorithm that uses n % 10 to get the ones digit and n / 10 to remove it, repeated in a while loop until n equals 0.
maximum value algorithmInitialize a max variable to the first value, then compare each subsequent value inside a loop and update max when a larger value is found.
object referenceA variable that holds a memory address pointing to an object. Using == on two reference variables checks whether they point to the same object.
null comparisonUse obj == null or obj != null to check whether a reference variable holds an object before calling methods on it.
count variableA variable incremented inside a loop only when a condition is true, used to count how many values meet a specific criterion.

How to review unit 2

Mistakes to avoid in Selection and Iteration

Using == to compare String content

== on two String variables checks whether they reference the same object, not whether they contain the same characters. Use .equals() to compare String content. This mistake causes code to behave correctly sometimes (when the JVM reuses the same literal) and fail other times.

Off-by-one errors in loop bounds

Using < n when you need <= n, or starting at 1 instead of 0, causes the loop to run one iteration too few or too many. For String traversal, valid indices are 0 through length() - 1, so a loop condition of i < s.length() is correct; i <= s.length() causes an IndexOutOfBoundsException.

Forgetting to update the loop variable in a while loop

If the variable that controls the while condition is never changed inside the loop body, the condition stays true forever and the loop never terminates. Always check that the loop body moves the control variable toward the termination condition.

Misapplying De Morgan's law

A common error is distributing the negation without flipping the operator: !(a && b) is NOT !a && !b. The correct form is !a || !b. Write out a small truth table to verify any De Morgan's transformation before trusting it.

Assuming the inner loop retains its value across outer iterations

In a nested for loop, the inner loop control variable is re-initialized every time the outer loop advances. Students sometimes trace as if the inner variable continues from where it left off, which produces incorrect output and execution counts.

Selection and Iteration on the AP exam

Tracing code to predict output

Multiple-choice questions frequently give a code segment with if statements, while loops, for loops, or nested loops and ask what value a variable holds or what the code prints. Practice tracing every statement in order, tracking variable values at each step, and applying short-circuit evaluation rules to compound conditions.

Writing and completing code segments

Free-response questions ask you to write methods that use selection and iteration to implement a described algorithm. Common tasks include counting values that meet a condition, finding a minimum or maximum, processing characters in a String, and combining loops with if statements. Identify the algorithm pattern first, then write the loop structure and condition.

Identifying equivalent or correct Boolean logic

Multiple-choice questions present two Boolean expressions and ask whether they are equivalent, or give a condition and ask which rewritten form produces the same result. Apply De Morgan's law, check operator precedence, and use a small truth table with two or three test cases to verify equivalence quickly.

Study unit 2 other ways

Unit 2 printables

Print the unit cheatsheets ($3) or unit exams ($5) for Unit 2. Yours to keep, no subscription needed.

get printables

Frequently Asked Questions

What's on the AP CSA Unit 2 progress check (MCQ and FRQ)?

The AP CSA Unit 2 progress check in AP Classroom includes both MCQ and FRQ parts drawn from the unit's 12 topics. The MCQ portion tests Boolean expressions, `if` and nested `if` statements, compound conditions, `while` loops, `for` loops, and informal run-time analysis. The FRQ portion asks you to write or trace code using selection and iteration, including string algorithms and nested loops. Working through the progress check is one of the best ways to find gaps before the real exam. You can find matched practice at AP CSA Unit 2.

How do I practice AP CSA Unit 2 FRQs?

AP CSA Unit 2 FRQs typically ask you to write methods that use `if` statements, `while` loops, `for` loops, or nested iteration to solve a problem, and string algorithm questions are common too. To practice, write out full method bodies by hand, trace through your logic step by step, and check edge cases like empty strings or loop boundaries. Focus especially on topics 2.9 (Implementing Selection and Iteration Algorithms) and 2.10 (Implementing String Algorithms), since those map most directly to free-response writing. Find practice problems at AP CSA Unit 2.

How should I study AP CSA Unit 2?

Start with Boolean expressions (topic 2.2) and `if` statements (2.3-2.5) before moving to loops, since selection logic is the foundation for everything else in this unit. Once conditions click, work through `while` loops (2.7) and `for` loops (2.8) separately, then practice nested iteration (2.11) and string algorithms (2.10) together since they combine both skills. Here's a concrete plan:
- Trace existing code by hand before writing your own, especially for nested loops.
- Write small methods from scratch for topics 2.9 and 2.10, then test edge cases.
- Use informal run-time analysis (2.12) to check whether your loops are efficient.
- Do a timed set of MCQs to catch tricky compound Boolean expression questions. Since this unit is 25-35% of the exam, it's worth revisiting it more than once. AP CSA Unit 2 has resources organized by topic to help you target weak spots.

Ready to review Unit 2?Start with the notes, check the topic cards, and use the practice or resource links when they are available for this course.