AP exam review verified for 2027

AP Computer Science A Unit 2 Review: Selection and Iteration

Review AP CSA Unit 2 to build fluency with selection and iteration, the two control structures that make programs respond to conditions and repeat work. This unit covers Boolean expressions, if statements, while and for loops, standard algorithms, and informal run-time analysis, and it carries 25-35% of the AP exam.

Use the topic guides, key terms, and available practice questions to work through every official topic from 2.1 to 2.12.

What is AP Computer Science A unit 2?

Unit 2 is the largest single unit on the AP CSA exam by weight. Every program you write from this point forward depends on selection and iteration, so the concepts here appear again in Unit 3 class creation and Unit 4 data collections.

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.

Selection: making decisions in code

Selection uses a Boolean expression that evaluates to true or false to decide which block of code runs. One-way selection (if) runs a block only when the condition is true. Two-way selection (if-else) picks between two blocks. Multiway selection (if-else-if) checks conditions in order and runs the first true branch, skipping the rest.

Iteration: repeating code with loops

A while loop checks its condition before every iteration and runs zero or more times. A for loop packs initialization, condition, and update into one header and is best when the number of iterations is known. Both loop types can cause infinite loops if the condition never becomes false, and both are vulnerable to off-by-one errors if bounds are set incorrectly.

Algorithms and analysis

Standard algorithms combine loops and conditionals to solve common problems: divisibility with %, digit extraction with % and /, frequency counting, min/max tracking, sum and average, and string traversal. Nested loops multiply iteration counts, and informal run-time analysis means tracing how many times each statement executes as input size grows.

The three building blocks of every algorithm

Every algorithm is built from sequencing (steps in order), selection (choosing a path based on a true or false condition), and repetition (repeating steps until a goal is reached). Unit 2 gives you the Java tools for all three, and the order in which you combine them determines what your program actually does. Getting this right is the foundation for every unit that follows.

AP Computer Science A unit 2 topics

2.1

Algorithms with Selection and Repetition

Introduces the three building blocks of algorithms: sequencing, selection, and repetition. You represent algorithms in plain language or diagrams before coding them in Java.

open guide
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.5

Compound Boolean Expressions

Introduces !, &&, and || with precedence order ! then && then ||. Short-circuit evaluation means the second operand may not be evaluated.

open guide
2.6

Comparing Boolean Expressions

Covers Boolean equivalence, truth tables, De Morgan's law, and comparing object references with == and != including null checks and .equals().

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.9

Implementing Selection and Iteration Algorithms

Standard algorithms using loops and conditionals: divisibility with %, digit extraction with % and /, frequency counting, min/max tracking, and sum/average with accumulators.

open guide
2.10

Implementing String Algorithms

String algorithms use charAt, substring, length, and indexOf inside loops to check substring properties, count matches, and build reversed strings.

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 snapshot

Hardest AP Computer A unit 2 topics

This snapshot uses Fiveable practice activity to show where students tend to miss questions and which review moves are worth prioritizing first.

70%average MCQ accuracy

Across 5.3k multiple-choice practice attempts for this unit.

5.3kMCQ attempts

Practice activity included in this snapshot.

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)

Practice AP Computer Science A unit 2 questions

Try AP-style multiple-choice questions and written prompts after you review the notes.

Example AP-style 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 = 10;

int n = 18;

int n = 34;

int n = 66;

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 distinct objects with identical text.

str1 and str2 reference the same object with identical text.

str1 and str2 reference distinct objects with different text.

str1 and str2 reference distinct objects of different lengths.

Example FRQs

open all FRQs
FRQ

Token stream processing and community guideline flagging

1. This question involves the CommentBuilder class, which is used to construct a user comment from a stream of text tokens. The CommentBuilder class uses a helper method getNextToken to retrieve tokens and a helper method isFlagged to check if a token violates community guidelines. You will write a constructor and a method in the CommentBuilder class.

</>Java
public class CommentBuilder
{
    private String comment; // To be initialized in part (a)
    private int tokenCount; // To be initialized in part (a)

    /**
     * Returns the next token to add to the comment, or null if
     * there are no more tokens available.
     */
    public String getNextToken()
    { /* implementation not shown */ }

    /**
     * Returns true if t is a flagged token (e.g., offensive or spam),
     * false otherwise.
     */
    public boolean isFlagged(String t)
    { /* implementation not shown */ }

    /**
     * Constructs a CommentBuilder object.
     * Builds a comment string by calling getNextToken repeatedly
     * up to maxTokens times or until getNextToken returns null.
     * The tokens are concatenated to the instance variable comment,
     * separated by a single space.
     * Updates tokenCount to the number of tokens added.
     * Precondition: maxTokens > 0
     */
    public CommentBuilder(int maxTokens)
    { /* to be implemented in part (a) */ }

    /**
     * Returns the number of flagged tokens in the instance variable comment.
     * Precondition: comment contains at least one token.
     *               Tokens in comment are separated by a single space.
     *               comment ends with a single space.
     */
    public int countFlaggedTokens()
    { /* to be implemented in part (b) */ }

    /* There may be instance variables, constructors, and methods
       that are not shown. */
}
a.

Write the CommentBuilder constructor, which uses a helper method to create a comment string. The constructor should initialize the instance variable comment to an empty string and tokenCount to 0. It should then repeatedly call the helper method getNextToken to obtain tokens. Each token obtained should be appended to comment followed by a single space, and tokenCount should be incremented. This process stops when either maxTokens tokens have been added OR getNextToken returns null.

A helper method, getNextToken, has been provided. Consecutive calls to getNextToken return the next available token in the stream. When there are no more tokens, getNextToken returns null.

Example 1

Consider the following calls to getNextToken. The return value of each call is used in the next call.
Method CallReturn Value
getNextToken()"This"
getNextToken()"is"
getNextToken()"great"
getNextToken()null
Based on these return values, a call to new CommentBuilder(5) should set the instance variable comment to "This is great " (note the trailing space) and set tokenCount to 3. The process stopped because getNextToken returned null.

Example 2

Consider the following calls to getNextToken.
Method CallReturn Value
getNextToken()"Spam"
getNextToken()"Spam"
getNextToken()"Spam"
Based on these return values, a call to new CommentBuilder(2) should set the instance variable comment to "Spam Spam " and set tokenCount to 2. The process stopped because the maximum number of tokens (2) was reached, even though more tokens were available.
Complete the CommentBuilder constructor.
/**
 * Constructs a CommentBuilder object.
 * Builds a comment string by calling getNextToken repeatedly
 * up to maxTokens times or until getNextToken returns null.
 * The tokens are concatenated to the instance variable comment,
 * separated by a single space.
 * Updates tokenCount to the number of tokens added.
 * Precondition: maxTokens > 0
 */
public CommentBuilder(int maxTokens)
b.

Write the countFlaggedTokens method, which returns the number of tokens in the instance variable comment that are considered flagged. You must use the helper method isFlagged to check each token. Assume that tokens in comment are separated by a single space and that comment ends with a space.

A helper method, isFlagged(String t), returns true if the token t is flagged (e.g., offensive or spam) and false otherwise.

Example 1

Assume the instance variable comment contains "This is bad " and the isFlagged method behaves as follows:
Method CallReturn Value
isFlagged("This")false
isFlagged("is")false
isFlagged("bad")true
The method countFlaggedTokens() should return 1.

Example 2

Assume the instance variable comment contains "Spam Spam " and isFlagged("Spam") returns true.
Method CallReturn Value
isFlagged("Spam")true
The method countFlaggedTokens() should return 2.
Complete the countFlaggedTokens method. You must use built-in String methods and the isFlagged helper method appropriately.
/**
 * Returns the number of flagged tokens in the instance variable comment.
 * Precondition: comment contains at least one token.
 *               Tokens in comment are separated by a single space.
 *               comment ends with a single space.
 */
public int countFlaggedTokens()

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.

Common unit 2 mistakes

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.

How this unit shows up 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.

Final unit 2 review checklist

  • Unit 2 final review checklist: Boolean expressionsWrite Boolean expressions using ==, !=, <, >, <=, >= and explain why == compares references for objects while .equals() compares content.
  • Unit 2 final review checklist: Selection statementsTrace one-way if, two-way if-else, multiway if-else-if, and nested if statements to identify exactly which branch runs for a given input.
  • Unit 2 final review checklist: Compound Boolean expressionsApply !, &&, and || with correct precedence, use short-circuit evaluation to predict which operands are evaluated, and apply De Morgan's law to rewrite negated conditions.
  • Unit 2 final review checklist: while and for loopsTrace while and for loops step by step, identify initialization, condition, body, and update, and convert between the two loop forms.
  • Unit 2 final review checklist: Standard algorithmsImplement and trace divisibility checks, digit extraction, frequency counting, min/max tracking, and sum/average using loops and accumulators.
  • Unit 2 final review checklist: String algorithmsWrite loops using charAt, substring, and length to check substring properties, count matches, and reverse a String.
  • Unit 2 final review checklist: Nested loops and run-time analysisTrace nested loops to predict output and count inner body executions; distinguish linear, quadratic, and triangular execution counts.

How to study unit 2

Step 1: Algorithms, Boolean expressions, and if statements (2.1-2.3)Read the topic guides for 2.1, 2.2, and 2.3. Practice writing Boolean expressions with all six relational operators and tracing one-way and two-way if statements with specific input values. Confirm you can explain why == fails for String content comparison.
Step 2: Nested if statements and compound Boolean expressions (2.4-2.6)Work through the topic guides for 2.4, 2.5, and 2.6. Trace multiway if-else-if chains with at least three branches. Practice applying De Morgan's law and build truth tables for && and || to verify equivalences. Use the key terms for short-circuit evaluation and De Morgan's law.
Step 3: while and for loops (2.7-2.8)Read the topic guides for 2.7 and 2.8. Write and trace at least three while loops and three for loops with different bounds. Convert each for loop to an equivalent while loop. Deliberately introduce an off-by-one error in one loop and explain what goes wrong.
Step 4: Standard algorithms and String algorithms (2.9-2.10)Work through the topic guides for 2.9 and 2.10. Implement each standard algorithm from scratch: divisibility, digit extraction, frequency count, min/max, sum/average, and String reversal. Trace each one with a specific input to verify correctness.
Step 5: Nested iteration and run-time analysis (2.11-2.12)Read the topic guides for 2.11 and 2.12. Trace nested loops with both independent and dependent bounds, listing every (i, j) pair. Calculate exact statement execution counts for single loops, independent nested loops, and triangular loops. Use the AP score calculator to estimate your estimated score range and identify which topic areas need more practice.

More ways to review

Topic study guides

Open the individual guides for Unit 2 when you want a closer review of one topic.

browse guides

FRQ practice

Practice free-response reasoning and compare your answer with scoring guidance.

practice FRQs

Cheatsheets

Use unit cheatsheets for a quick visual review after you work through the notes.

open cheatsheets

Score calculator

Estimate your broader AP score goal after you review the course and exam format.

open calculator

Frequently Asked Questions

What topics are covered in AP CSA Unit 2?

AP CSA Unit 2 covers 12 topics focused on selection and iteration: Algorithms with Selection and Repetition, Boolean Expressions, `if` Statements, Nested `if` Statements, Compound Boolean Expressions, Comparing Boolean Expressions, `while` Loops, `for` Loops, Implementing Selection and Iteration Algorithms, Implementing String Algorithms, Nested Iteration, and Informal Run-Time Analysis. These topics build on each other, so Boolean expressions come before `if` statements, and single loops come before nested iteration. See AP CSA Unit 2 for practice on all 12 topics.

How much of the AP CSA exam is Unit 2?

AP CSA Unit 2 makes up 25-35% of the AP exam, making it one of the heaviest-weighted units on the test. It covers selection (Boolean expressions, `if` statements, compound conditions) and iteration (`while` loops, `for` loops, nested iteration), which means these concepts show up constantly across both the multiple-choice and free-response sections.

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.

Where can I find AP CSA Unit 2 practice questions?

For AP CSA Unit 2 practice questions, including multiple-choice and practice test problems, head to AP CSA Unit 2. You'll find MCQ-style questions covering Boolean expressions, `if` statements, `while` and `for` loops, nested iteration, and run-time analysis, plus FRQ practice for string algorithms and implementing selection and iteration. Mixing MCQ drills with written FRQ attempts is the most effective way to prep for this unit's 25-35% exam weight.

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.