AP CSA Unit 2 Study Guide 2026 | Selection & Iteration

AP CSA Unit 2 Study Guide | 2025-2026

AP CSA Unit 2 Study Guide 2026 | Selection & Iteration

AP Computer Science A

Unit 2: Selection and Iteration

Complete Study Guide — 2025-2026 Curriculum

25-35% of AP Exam

📚 Unit Overview

Unit 2: Selection and Iteration is one of the most critical units in AP Computer Science A. This unit combines decision-making (selection) with repetition (iteration) to form the foundation of algorithmic problem-solving.

📝 AP Exam Insight If you can comfortably trace if-statements and loops, most AP CSA multiple-choice questions become much easier. Many FRQs are essentially loops and conditionals with specific contexts.

What You'll Learn

  • How programs make decisions using boolean expressions and if statements
  • How programs repeat code using while and for loops
  • How to combine selection and iteration to implement algorithms
  • How to analyze code efficiency through informal runtime analysis
  • How to trace and debug code involving conditionals and loops

Unit 2 Topics at a Glance

Topic Description Exam Weight
Boolean Expressions Relational and logical operators, truth tables High
if Statements Single selection, if-else, if-else-if chains High
Nested Conditionals if statements inside other if statements Medium
De Morgan's Law Simplifying boolean expressions Medium
while Loops Condition-controlled repetition High
for Loops Counter-controlled repetition High
Nested Loops Loops inside other loops High
String Algorithms Processing strings with loops High

🔢 Boolean Expressions & Relational Operators

A boolean expression is an expression that evaluates to either true or false. Boolean expressions are the foundation of all decision-making in Java programs.

The boolean Data Type

Java has a primitive data type called boolean that can hold exactly two values: true or false.

boolean isRaining = true;
boolean hasUmbrella = false;
boolean isSunny = !isRaining;  // false

// Boolean expressions evaluate to boolean values
int age = 18;
boolean isAdult = age >= 18;   // true

Relational Operators

Operator Name Example Result (if x = 7)
== Equal to x == 7 true
!= Not equal to x != 7 false
> Greater than x > 5 true
< Less than x < 5 false
>= Greater than or equal x >= 7 true
<= Less than or equal x <= 10 true
⚠️ Warning Remember: == tests for equality (two equal signs), while = is assignment (one equal sign). This is a very common source of errors!

Comparing Strings: equals() vs ==

One of the most common mistakes in Java is using == to compare Strings. Always use the equals() method to compare String content.

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

// Using == (compares references) - WRONG!
System.out.println(s1 == s2);     // true (due to String pooling)
System.out.println(s1 == s3);     // false (different objects!)

// Using equals() (compares content) - CORRECT!
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
📝 AP Exam Tip On the AP exam, ALWAYS use .equals() to compare Strings. Using == for Strings is a guaranteed point deduction on FRQs.
✓✗ Practice Boolean Expressions 2 questions

🔗 Logical Operators & Truth Tables

Logical operators allow you to combine multiple boolean expressions into more complex conditions.

The AND Operator (&&)

Returns true only if BOTH conditions are true.

int age = 25;
boolean hasLicense = true;

// Both conditions must be true
boolean canDrive = age >= 16 && hasLicense;  // true

// Practical example: checking a range
int temperature = 72;
boolean comfortable = temperature >= 65 && temperature <= 78;  // true

The OR Operator (||)

Returns true if AT LEAST ONE condition is true.

boolean isWeekend = true;
boolean isHoliday = false;

// At least one must be true
boolean dayOff = isWeekend || isHoliday;  // true

The NOT Operator (!)

Reverses a boolean value: true becomes false and vice versa.

boolean isRaining = true;
boolean notRaining = !isRaining;  // false

Truth Tables

AND (&&)

A B A && B
true true true
true false false
false true false
false false false

OR (||)

A B A || B
true true true
true false true
false true true
false false false

NOT (!)

A !A
true false
false true

Short-Circuit Evaluation

Java uses short-circuit evaluation for && and ||:

  • For &&: If the first condition is false, the second is never evaluated
  • For ||: If the first condition is true, the second is never evaluated
// Short-circuit prevents division by zero!
int x = 0;
if (x != 0 && 10 / x > 1) {
    System.out.println("Safe division");
}
// x != 0 is false, so 10/x is NEVER evaluated (no error!)
📝 AP Exam Tip Short-circuit evaluation appears frequently on AP MCQs! Questions often test whether you understand that the second condition may not be evaluated.
&& Practice Logical Operators 2 questions

🔄 De Morgan's Law

De Morgan's Law provides rules for distributing a NOT operator over AND and OR expressions.

The Two Rules

Rule 1: !(A && B) = !A || !B

NOT (A AND B) equals (NOT A) OR (NOT B)

Rule 2: !(A || B) = !A && !B

NOT (A OR B) equals (NOT A) AND (NOT B)

Memory trick: When you distribute the NOT, the operator flips (AND becomes OR, OR becomes AND).

De Morgan's Law Reference Table

Original Apply De Morgan's Equivalent
!(A && B) Flip && to ||, negate both !A || !B
!(A || B) Flip || to &&, negate both !A && !B
!(x > 5 && y < 10) Negate comparisons, flip to || x <= 5 || y >= 10
!(x >= 1 && x <= 10) Range check negation x < 1 || x > 10

Practical Example

// Checking if x is NOT between 1 and 10 (inclusive)

// Method 1: Direct negation
if (!(x >= 1 && x <= 10)) {
    System.out.println("x is outside the range");
}

// Method 2: Applying De Morgan's Law (equivalent)
if (x < 1 || x > 10) {
    System.out.println("x is outside the range");
}
📝 AP Exam Tip De Morgan's Law questions appear on almost every AP CSA exam. Practice transforming expressions in both directions until it becomes automatic.
¬ Practice De Morgan's Law 2 questions

🔀 Selection with if Statements

Selection statements allow your program to make decisions and execute different code based on conditions.

Basic if Statement

if (condition) {
    // code executes only if condition is true
}

// Example
int number = 5;
if (number > 0) {
    System.out.println(number + " is positive");
}

if-else Statement

int score = 55;
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
// Output: Fail

if-else-if Chain

Only the FIRST true condition's block executes—once a block runs, the rest are skipped.

int score = 85;
String grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}
System.out.println("Grade: " + grade);  // Output: Grade: B
⚠️ Warning Order matters in if-else-if chains! Always check the most restrictive condition first. If you checked score >= 60 first, everyone passing would get a D.

Multiple Independent if Statements

Separate if statements (without else) are evaluated independently—multiple blocks can execute:

int x = 12;

// These are SEPARATE if statements - all can execute
if (x % 2 == 0) {
    System.out.println("x is even");
}
if (x % 3 == 0) {
    System.out.println("x is divisible by 3");
}
if (x > 10) {
    System.out.println("x is greater than 10");
}

// Output:
// x is even
// x is divisible by 3
// x is greater than 10
🔀 Practice if Statements 3 questions

🔁 Iteration with while Loops

The while loop is the most fundamental form of iteration—it repeats as long as a condition remains true.

while Loop Syntax

while (condition) {
    // loop body - executes repeatedly while condition is true
    // MUST modify something to eventually make condition false!
}

// Example: Count from 1 to 5
int count = 1;
while (count <= 5) {
    System.out.println(count);
    count++;  // CRITICAL: update the loop control variable
}
// Output: 1 2 3 4 5

The Three Parts of a while Loop

Part Purpose Example
1. Initialization Set up the loop control variable BEFORE the loop int i = 0;
2. Condition Tested BEFORE each iteration while (i < 10)
3. Update Modify the loop variable INSIDE the body i++;
📌 Important The condition is checked BEFORE each iteration, including the first one. If the condition is false initially, the loop body never executes at all (zero iterations).

Common while Loop Patterns

int n = 12345;
int sum = 0;
while (n > 0) {
    sum += n % 10;  // Add last digit to sum
    n /= 10;        // Remove last digit
}
System.out.println("Sum of digits: " + sum);  // Output: 15
int num = 12345;
int count = 0;
while (num > 0) {
    count++;       // Count digits
    num /= 10;     // Remove last digit
}
System.out.println("Digits: " + count);  // Output: 5
int original = 12345;
int reversed = 0;
int num = original;

while (num > 0) {
    int digit = num % 10;              // Get last digit
    reversed = reversed * 10 + digit;  // Append to result
    num /= 10;                         // Remove last digit
}
System.out.println("Reversed: " + reversed);  // Output: 54321

🔄 Step-Through Tracer: while Loop

Watch how the loop control variable changes each iteration. Notice when the condition becomes false and the loop exits.

int n = 1;
while (n <= 16) {
    n = n * 2;
}
Ready — click Next Step to begin
n1
n ≤ 16??
Check # n before n ≤ 16? Action n after
🔁 Practice while Loops 2 questions

🔂 Iteration with for Loops

The for loop is ideal when you know in advance how many times you want to repeat. It combines initialization, condition, and update into a single, compact header line.

for Loop Syntax

for (initialization; condition; update) {
    // loop body
}

// Example: Print 0 through 4
for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");
}
// Output: 0 1 2 3 4

// Example: Count by 2s
for (int i = 0; i <= 10; i += 2) {
    System.out.print(i + " ");
}
// Output: 0 2 4 6 8 10

for Loop Execution Order

  1. Initialization executes ONCE at the very beginning
  2. Condition is checked BEFORE each iteration
  3. If condition is true, the loop body executes
  4. Update executes AFTER each iteration of the body
  5. Return to step 2 and repeat

for Loop vs while Loop Equivalence

// for loop version
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

// Equivalent while loop version
int i = 0;           // Initialization moved before loop
while (i < 5) {      // Condition stays the same
    System.out.println(i);
    i++;             // Update moved to end of body
}

🔄 Step-Through Tracer: for Loop

Click Next Step to execute one step at a time and watch how each variable changes. Predict what happens before you click.

for (int i = 0; i < 5; i++) {
    sum = sum + i;
}
Ready — click Next Step to begin
i?
sum0
condition?
Step Phase i sum i < 5? Action
💡 Tip Use a for loop when you know the number of iterations in advance. Use a while loop when the number of iterations depends on a condition that's checked during execution.

🔄 Nested Loops

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.

Basic Nested Loop

for (int outer = 1; outer <= 3; outer++) {
    for (int inner = 1; inner <= 4; inner++) {
        System.out.print("(" + outer + "," + inner + ") ");
    }
    System.out.println();
}

/* Output:
(1,1) (1,2) (1,3) (1,4)
(2,1) (2,2) (2,3) (2,4)
(3,1) (3,2) (3,3) (3,4)

Total iterations: 3 × 4 = 12
*/

Calculating Nested Loop Iterations

To find the total number of times a nested loop body executes, multiply the iteration counts:

// How many times does "X" print?
for (int i = 0; i < 5; i++) {        // 5 iterations
    for (int j = 0; j < 3; j++) {    // 3 iterations each
        System.out.print("X");
    }
}
// Answer: 5 × 3 = 15 times

Common Pattern: Triangle

// Print a right triangle
for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("*");
    }
    System.out.println();
}
/* Output:
*
**
***
****
*****
*/

🔄 Step-Through Tracer: Nested Loop Grid

See exactly which cell (outer, inner) is visited at each step. This is how 2D array traversal works too.

for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 4; c++) {
        // visit cell (r, c)
    }
}
Ready — click Next Step
r (outer)0
c (inner)0
iterations0

Total iterations = 3 × 4 = 12. Multiply outer × inner loop counts.

📝 AP Exam Tip When a nested loop MCQ asks "How many times does this print?", multiply the loop counts unless a condition or break interrupts the flow.
🔄🔄 Practice Nested Loops 2 questions

📈 Accumulator & Loop Algorithm Patterns

FRQ Question 1 tests these patterns year after year. Every pattern below has appeared on a released AP CSA exam. Master the template, then apply it to any data.

∑ Sum / Total

int sum = 0;                    // initialize OUTSIDE loop
for (int x : arr) {
    sum += x;                   // accumulate
}
System.out.println(sum);
⚠ Trap: initializing sum inside the loop resets it every iteration — you get only the last value.

📈 Max / Min

int max = arr[0];               // initialize to FIRST element, NOT 0
for (int i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}
System.out.println(max);
⚠ Trap: initializing max to 0 breaks when all values are negative. Always use arr[0] or Integer.MIN_VALUE.

✓ Count / Tally

int count = 0;
for (String s : words) {
    if (s.length() > 5) {
        count++;
    }
}
System.out.println(count);
⚠ Trap: the condition inside the loop is where bugs hide. Trace carefully with boundary values (exactly length 5).

🔍 Linear Search / Find

int target = 42;
int foundAt = -1;               // -1 means "not found"
for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) {
        foundAt = i;
        break;                  // stop once found
    }
}
if (foundAt != -1) {
    System.out.println("Found at index " + foundAt);
} else {
    System.out.println("Not found");
}
⚠ Trap: forgetting the -1 sentinel. The AP exam often asks what the method returns when the value is NOT in the array.

🔄 Running Product

int product = 1;                // initialize to 1, NOT 0
for (int x : arr) {
    product *= x;
}
System.out.println(product);
⚠ Trap: initializing product to 0 makes everything 0 — multiplying by 0 is always 0.

📝 Build a String

String result = "";             // empty string, NOT null
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (Character.isUpperCase(c)) {
        result += c;            // concatenate matching chars
    }
}
System.out.println(result);
⚠ Trap: using null instead of "" causes NullPointerException on the first concatenation.
🎯 AP Exam Pattern Recognition

On FRQ Q1, underline the output type (int, String, boolean, void) before writing any code. That tells you which pattern to use:

  • Returns int with a numeric result → Sum, Max, or Count pattern
  • Returns int that could be -1 → Linear Search pattern
  • Returns String built from input → String Builder pattern
  • Returns boolean → often a search with early return true, return false after loop

📝 String Algorithms

String processing is a major topic in AP CSA. You'll use loops to traverse strings character by character.

Essential String Methods

Method Returns Description
length() int Number of characters
substring(a, b) String Characters from index a to b-1
substring(a) String Characters from index a to end
indexOf(str) int First index of str, or -1 if not found
equals(str) boolean True if equal content

String Traversal

// String traversal using substring()
String word = "Java";
for (int i = 0; i < word.length(); i++) {
    String letter = word.substring(i, i + 1);
    System.out.print(letter + " ");
}
// Output: J a v a

Common String Algorithms

public int countVowels(String str) {
    String vowels = "aeiouAEIOU";
    int count = 0;
    
    for (int i = 0; i < str.length(); i++) {
        String letter = str.substring(i, i + 1);
        if (vowels.indexOf(letter) != -1) {
            count++;
        }
    }
    return count;
}
public String reverse(String str) {
    String reversed = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        reversed += str.substring(i, i + 1);
    }
    return reversed;
}

// Usage
String result = reverse("hello");  // Returns "olleh"
public boolean isPalindrome(String str) {
    String reversed = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        reversed += str.substring(i, i + 1);
    }
    return str.equals(reversed);
}

// Usage
isPalindrome("racecar");  // Returns true
isPalindrome("hello");    // Returns false
public String removeChar(String str, String toRemove) {
    String result = "";
    for (int i = 0; i < str.length(); i++) {
        String current = str.substring(i, i + 1);
        if (!current.equals(toRemove)) {
            result += current;
        }
    }
    return result;
}

// Usage
removeChar("Mississippi", "s");  // Returns "Miiippi"

⚠️ Common Errors and How to Avoid Them

1. Infinite Loops

// WRONG: n never changes
int n = 10;
while (n > 0) {
    System.out.println(n);
    // Missing: n--;
}

// CORRECT
int n = 10;
while (n > 0) {
    System.out.println(n);
    n--;  // Update the variable!
}

2. Off-By-One Errors

// WRONG: Prints 1 through 4 (one too few)
for (int i = 1; i < 5; i++) {
    System.out.print(i + " ");  // Output: 1 2 3 4
}

// CORRECT: Prints 1 through 5
for (int i = 1; i <= 5; i++) {
    System.out.print(i + " ");  // Output: 1 2 3 4 5
}

3. Using == with Strings

// WRONG
if (s1 == s2) { ... }

// CORRECT
if (s1.equals(s2)) { ... }

4. Misplaced Semicolons

// WRONG: Semicolon after if
if (x > 5);  // Empty statement!
{
    System.out.println("x is large");  // ALWAYS runs
}

// CORRECT
if (x > 5) {
    System.out.println("x is large");
}
💡 Tip Always use braces {} with if statements and loops, even for single-line bodies. This prevents many common bugs.
🐛 Practice Debugging & Edge Cases 2 questions
🎯 Unit 2 Comprehensive Review 2 questions

✍ Practice Questions

These questions match actual AP exam difficulty. Predict your answer before reading the options. 15 questions covering all Unit 2 topics.

Score:0 / 0
1. What is the output of the following code? TRACE before choosing.
int count = 1;
while (count <= 10) {
    System.out.print(count + " ");
    count++;
}
2. A student writes the following code intending to sum 1+2+3+4+5. IDENTIFY the error.
1: int total = 0;
2: for (int k = 1; k <= 5; k++);
3: {
4:     total += k;
5: }
6: System.out.println(total);
3. Consider these three statements about boolean evaluation in Java. WHICH are correct?

I. In x > 0 && y < 10, if x > 0 is false, y < 10 is never evaluated.
II. In x > 0 || y < 10, if x > 0 is false, y < 10 is never evaluated.
III. !(a && b) is equivalent to !a || !b.
4. How many times does System.out.println() execute?
for (int i = 0; i < 3; i++) {
    for (int j = 0; j <= i; j++) {
        System.out.println(i + " " + j);
    }
}
5. IDENTIFY the bug in this max-finding method.
public static int findMax(int[] nums) {
    int max = 0;
    for (int val : nums) {
        if (val > max) {
            max = val;
        }
    }
    return max;
}
// Called with: findMax(new int[]{-5, -3, -8})
6. What is the value of n after this loop completes?
int n = 1;
while (n <= 100) {
    n *= 2;
}
7. Which of the following are true about for loops in Java? WHICH apply?

I. A for loop is preferred when the number of iterations is known before the loop starts.
II. A for loop body always executes at least once.
III. The initialization in a for loop executes once each time the condition is checked.
8. Under what conditions is !(p || q) equal to true, where p is x > 3 and q is y < 10?
9. What does the following method return when called with an array {1, 2, 3, 4}?
public static int firstEven(int[] arr) {
    for (int val : arr) {
        if (val % 2 == 0) {
            return val;
        }
    }
    return -1;
}
10. What does the following return when called with countChar("hello", 'l')?
public static int countChar(String s, char target) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == target) {
            count++;
        }
    }
    return count;
}
11. Consider three loop headers that attempt to traverse an array arr. WHICH contain an error?

I. for (int i = 0; i <= arr.length; i++)
II. for (int i = 0; i < arr.length; i++)
III. for (int i = 0; i <= arr.length - 1; i++)
12. What is the output? TRACE carefully — count the if statements.
int x = 5;
if (x > 3) {
    System.out.print("A");
} else if (x > 1) {
    System.out.print("B");
} else {
    System.out.print("C");
}
if (x > 0) {
    System.out.print("C");
}
13. IDENTIFY why this method returns the wrong answer when called with {1,2,3,4,5}.
public static int doubleSum(int[] arr) {
    for (int val : arr) {
        int result = 0;
        result += val * 2;
    }
    return result;
}
14. Which statements about short-circuit evaluation are correct? WHICH apply?

I. In a & b (single &), if a is false, b is not evaluated.
II. In a || b, if a is true, b is not evaluated.
III. Writing x != 0 && 100/x > 5 is safer than 100/x > 5 && x != 0 to avoid division by zero.
15. What is the sum of all values printed by the following nested loop?
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.println(i * j);
    }
}

📋 Quick Reference

Relational Operators

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

Logical Operators

Operator Meaning Short-Circuit
&& AND Stops if first is false
|| OR Stops if first is true
! NOT N/A

De Morgan's Law

Original Equivalent
!(A && B) !A || !B
!(A || B) !A && !B

Common Loop Patterns

// Counter
int count = 0;
for (...) { if (condition) count++; }

// Accumulator
int sum = 0;
for (...) { sum += value; }

// String traversal
for (int i = 0; i < str.length(); i++) {
    String ch = str.substring(i, i + 1);
}

// Digit extraction
while (n > 0) {
    int digit = n % 10;
    n /= 10;
}
1-on-1 Tutoring
Still unsure after studying? Work directly with Tanner before the exam.
11+ years teaching AP CSA — 54.5% of students score 5s vs. 25.5% nationally.
See Tutoring Options →
AP CSA Exam — May 15, 2026
Where are you right now?
Choose the prep path that matches your situation — not just a product.
Days until exam: days
Best for you now Phase 1 — Study
Just Getting Started
You have time to build a real foundation
Work through the unit study guides in order. Understanding the material deeply now means less panic later — and higher scores on both the MCQ and FRQ.
Start with Study Guides → Free: try a daily practice question Or get a day-by-day plan from the start →
Best for you now Phase 2 — Practice
I Know It — I Need Reps
You understand the concepts but haven't tested yourself yet
The fastest way to find gaps is a full exam under timed conditions. Your weak spots will surface immediately — and you'll know exactly where to focus your remaining time.
Take a Full Practice Exam → Free: browse the FRQ archive (2019–2025) → Or get the 2025 FRQ Year Pack with full solutions →
Best for you now Phase 3 — Focused Review
Running Out of Time
1–3 weeks out and you need a focused plan
Stop browsing random topics. A day-by-day cram plan tells you exactly what to cover each day so nothing important gets skipped and nothing gets over-studied.
Get the Cram Kit → Free: grab the Quick Reference Sheet Or add expert tutoring alongside the plan →
Best for you now Phase 4 — Exam Mode
Exam Is Days Away
You need the fastest path to points right now
days until AP CSA exam
One focused tutoring session with someone who knows exactly what the exam tests is worth more than 10 more hours studying solo. Lock in a slot before they fill up.
Book a Tutor Session → Or get the Cram Kit for a self-study plan
Exam's done — good luck on scores.
AP CSA scores release in July. In the meantime, check out what your score means for college credit and what to expect next.
Browse All AP CSA Resources →

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]