AP CSA Unit 2: Selection & Iteration - Complete Study Guide (2025)

AP Computer Science A – Unit 2: Selection and Iteration (2025)

Unit 2 combines selection (making decisions with if statements) and iteration (repeating actions with loops). Together, these skills account for roughly 25–35% of the AP CSA exam and show up in almost every FRQ and MCQ.

📘 2.1 Unit Overview & Big Ideas

In this unit, you’ll learn how programs:

  • Decide what to do using boolean expressions and if statements
  • Repeat code using while and for loops
  • Combine decisions and repetition to implement algorithms

Main topics:

  • Relational & logical operators (>, <, ==, !=, &&, ||, !)
  • Boolean expressions and truth tables
  • if, else-if, else, and nested conditionals
  • De Morgan’s Law and simplifying conditions
  • while loops, for loops, and nested loops
  • Loop patterns: counting, summing, searching
  • Off-by-one errors and infinite loops
  • Tracing and debugging selection + iteration
AP Exam Insight: If you can comfortably trace if-statements and loops, most AP CSA multiple-choice questions become much easier. Many FRQs are just “nicer looking” loops and conditionals.

🧠 2.2 Boolean Expressions & Relational Operators

A boolean expression is an expression that evaluates to either true or false. You’ll use these inside if-statements and loops.

Relational Operators

Operator Meaning Example
== equal to x == 5
!= not equal to x != 0
> greater than score > 90
< less than temp < 32
>= greater than or equal to age >= 16
<= less than or equal to count <= 10

Examples

int x = 7;
boolean a = (x > 5);    // true
boolean b = (x == 7);   // true
boolean c = (x != 7);   // false
Important: == compares values of primitives (like int, double). For Strings, you must use equals(), not ==.

🔗 2.3 Logical Operators, Truth Tables & Precedence

Logical operators combine or modify boolean values:

  • && (AND) – true only if both conditions are true
  • || (OR) – true if at least one condition is true
  • ! (NOT) – reverses a boolean value

Truth Table

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

NOT Operator

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

Operator Precedence (Simplified)

  • Relational: >, <, >=, <=, ==, !=
  • Logical NOT: !
  • Logical AND: &&
  • Logical OR: ||
Use parentheses generously. They improve readability and prevent mistakes, especially under exam pressure.

Short-Circuit Evaluation

Java uses short-circuiting:

  • A && B → if A is false, B is never evaluated
  • A || B → if A is true, B is never evaluated
if (x != 0 && 10 / x > 1) {
    // safe: 10/x only happens if x != 0
}
AP Tip: Many MCQs rely on short-circuit logic to avoid runtime errors like division by zero.

🧩 2.4 De Morgan’s Law & Simplifying Conditions

De Morgan’s Law lets you distribute a NOT over an AND/OR expression:

!(A && B) == (!A || !B) !(A || B) == (!A && !B)

Example

Suppose we want to check that a value x is outside the range 1 to 10:

// x is NOT between 1 and 10 inclusive:
if (x < 1 || x > 10) {
    ...
}

// Equivalent to:
if (!(x >= 1 && x <= 10)) {
    ...
}
De Morgan’s Law appears frequently on AP questions that ask for equivalent boolean expressions.

🔀 2.5 if, else-if, else – Making Decisions

Selection lets your program choose between different paths of execution.

Basic if Statement

if (condition) {
    // runs only if condition is true
}

if-else

if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

if-else-if Chain

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else {
    grade = "D or F";
}
Only the first true condition in an if/else-if/else chain executes. Once one block runs, the rest are skipped.

Example – Two Separate if Statements

int x = 12;

if (x % 2 == 0)
    System.out.println("even");

if (x % 3 == 0)
    System.out.println("divisible by 3");

Output:

  • even
  • divisible by 3

Because these are two separate if statements, both can run.

🏛 2.6 Nested Conditionals & Common Decision Patterns

You can place an if-statement inside another if or else block. This is called a nested conditional.

Nested Example

if (age >= 16) {
    if (hasPermit) {
        System.out.println("You can drive.");
    } else {
        System.out.println("Get your permit first.");
    }
} else {
    System.out.println("Too young to drive.");
}

Range Checking Pattern

if (score < 0 || score > 100) {
    System.out.println("Invalid score");
} else if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'D';
}

Multi-Condition Decisions

if (gpa >= 3.5 && communityServiceHours >= 50) {
    eligibleForScholarship = true;
}
When tracing nested conditions, write down the values of variables and follow the structure step by step. Don’t try to “eyeball” complex logic.

🧪 2.7 Selection Practice – Predict the Output

Example 1

int x = 5;
if (x > 10)
    System.out.println("big");
else if (x > 3)
    System.out.println("medium");
else
    System.out.println("small");

Output: medium

Example 2

int a = 4;
int b = 7;

if (a > b || b % 2 == 1)
    System.out.println("A");
else if (a % 2 == 0 && b % 2 == 0)
    System.out.println("B");
else
    System.out.println("C");

Output: A (because b % 2 == 1 is true)

Example 3

boolean hot = true;
boolean sunny = false;

if (!hot && sunny)
    System.out.println("Cool day");
else if (hot && !sunny)
    System.out.println("Humid");
else
    System.out.println("Mixed");

Output: Humid

When you see selection-heavy MCQs, treat them like these small exercises: copy the values mentally, then follow each branch carefully.

🔁 2.8 Introduction to Iteration (Loops)

Iteration means repeating a block of code multiple times. In Java, the main loop constructs are:

  • while loops – repeat while a condition is true
  • for loops – repeat a specific number of times
  • nested loops – loops inside loops
while (condition) { // repeated code } for (initialization; condition; update) { // repeated code }
Almost every algorithm you write in AP CSA will use some combination of if-statements and loops.

🔂 2.9 while Loops – Condition-Controlled Repetition

A while loop repeats as long as its condition evaluates to true.

while (condition) {
    // body runs repeatedly
}

Counting Example

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

Output: 0 1 2 3 4

Key Points

  • The condition is checked before each iteration.
  • The loop body may run zero times if the condition starts false.
  • You must change something inside the loop so the condition eventually becomes false.

Common Mistake – Infinite Loop

int n = 10;
while (n > 0) {
    System.out.println(n);
    // n never changes → infinite loop
}
Always identify the loop variable and verify it changes every iteration in the direction that makes the condition false.

🧩 Mastering Loops Without Arrays

Before moving on to classes (Unit 3) and data collections (Unit 4), you should be fully comfortable with loops that operate on:

  • integers (counting, summing, reversing)
  • Strings (traversal, searching, building new strings)
  • boolean conditions (flags, early exit with break)
  • sentinel logic (looping until a condition becomes false)

These loop skills are essential for the AP CSA exam and appear heavily in MCQs and early FRQs—even before arrays show up.

Remember: Unit 2 is about controlling repetition using while and for loops—not about data structures yet. Arrays and ArrayLists come later in Unit 4.

🔤 Looping Through Characters in a String

Strings are perfect for practicing iteration. You can examine, count, or modify characters using length() and charAt(i).

Example: Count the vowels in a String

String word = "computer science";
int count = 0;

for (int i = 0; i < word.length(); i++) {
    char ch = word.charAt(i);
    if ("aeiouAEIOU".indexOf(ch) != -1) {
        count++;
    }
}

System.out.println("Vowels: " + count);
    

Example: Reverse a String

String original = "hello";
String reversed = "";

for (int i = original.length() - 1; i >= 0; i--) {
    reversed += original.charAt(i);
}

System.out.println(reversed); // "olleh"
    
AP Tip: String traversal with charAt() appears frequently on MCQs and FRQs. Master it before moving to arrays.

🎯 Essential Loop Patterns (Without Arrays)

1. Counter Loop

Counts occurrences of something:

int count = 0;
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        count++;
    }
}
System.out.println(count); // 5 even numbers
    

2. Accumulator Loop

Adds values together:

int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println(sum); // 5050
    

3. Flag Loop

Stops early when something is found:

String s = "aP cSa test";
boolean found = false;

for (int i = 0; i < s.length(); i++) {
    if (Character.isUpperCase(s.charAt(i))) {
        found = true;
        break;
    }
}

System.out.println(found); // true
    

4. Sentinel Loop (While Loop)

Scanner input = new Scanner(System.in);
System.out.print("Enter a positive number (-1 to stop): ");
int num = input.nextInt();

while (num != -1) {
    System.out.println("You entered: " + num);
    num = input.nextInt();
}
    
Notice: All four patterns appear in the AP CSA exam—often disguised inside FRQs.

📐 Looping Without Collections — Math-Based Problems

Example: Count the digits in a number

int n = 483902;
int digits = 0;

while (n > 0) {
    n /= 10;   // remove last digit
    digits++;
}

System.out.println(digits); // 6
    

Example: Check if a number is prime

int num = 37;
boolean isPrime = true;

for (int i = 2; i < num; i++) {
    if (num % i == 0) {
        isPrime = false;
        break;
    }
}

System.out.println(isPrime);
    

Example: Sum digits of a number

int n2 = 762;
int sumDigits = 0;

while (n2 > 0) {
    sumDigits += n2 % 10;
    n2 /= 10;
}

System.out.println(sumDigits); // 15
    
AP Tip: These examples reinforce the idea that loops are about logic and repetition—not just data traversal.

🔁 Nested Loop Patterns (No Arrays Needed)

Triangle Pattern

for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("*");
    }
    System.out.println();
}
    

Grid Pattern

for (int r = 1; r <= 3; r++) {
    for (int c = 1; c <= 5; c++) {
        System.out.print("#");
    }
    System.out.println();
}
    
Why this matters: Loop tracing is over 20% of AP CSA MCQs, and many involve nested loops producing patterns.

📝 Practice Problems — Unit 2 Mastery Check (No Arrays Yet)

Try these practice problems to test your understanding of Unit 2 loops before you move on:

  • Write a loop that counts how many characters in a String are digits (hint: Character.isDigit()).
  • Given a String, determine whether it contains three consecutive vowels.
  • Use a while loop to reverse an integer (for example, 12345 becomes 54321).
  • Write a for loop that prints every other character in a String starting at index 0.
  • Write a nested loop that prints a 5x5 grid of numbers from 1 to 25 in row-major order.
These problems prepare you for Unit 3 constructors/methods and Unit 4 arrays without jumping ahead.

📝 Unit 2 Quiz – Selection & Iteration (10 Questions)

Question 1

What is printed by the following code?

int x = 7;

if (x > 5 && x < 10) {
    System.out.println("A");
} else {
    System.out.println("B");
}
  • A. A
  • B. B
  • C. Nothing
  • D. Causes a runtime error

Answer: A
Both conditions (x > 5 and x < 10) are true, so the if block runs.

Question 2

What is the value of count after this code runs?

int count = 0;

for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) {
        count++;
    }
}
  • A. 2
  • B. 3
  • C. 4
  • D. 5

Answer: B
Numbers divisible by 3 between 1 and 10 are 3, 6, and 9 → 3 total.

Question 3

What is printed?

int x = 0;

if (x != 0 && 10 / x > 1) {
    System.out.println("Yes");
} else {
    System.out.println("No");
}
  • A. Yes
  • B. No
  • C. Runtime error
  • D. Nothing

Answer: B
Because of short-circuit evaluation, 10 / x is never evaluated when x != 0 is false.

Question 4

What is printed?

int n = 5;

while (n > 0) {
    n -= 2;
    System.out.print(n + " ");
}
  • A. 3 1 -1
  • B. 3 1
  • C. 5 3 1
  • D. Infinite loop

Answer: A
Values printed after subtraction: 3, 1, -1. Loop stops once n is no longer > 0.

Question 5

Which boolean expression correctly checks if x is between 10 and 20 inclusive?

  • A. x >= 10 || x <= 20
  • B. x > 10 && x < 20
  • C. x >= 10 && x <= 20
  • D. !(x < 10 && x > 20)

Answer: C
Inclusive range requires both bounds using &&.

Question 6

What is printed?

String s = "java";
int i = 0;

while (i < s.length()) {
    if (s.charAt(i) == 'a') {
        System.out.print(i + " ");
    }
    i++;
}
  • A. 0 2
  • B. 1 3
  • C. 2 4
  • D. 1 2

Answer: B
Indices: j=0, a=1, v=2, a=3 → 'a' occurs at indices 1 and 3.

Question 7

Which loop correctly prints the numbers 1 through 5?

  • A.
    for (int i = 1; i < 5; i++)
  • B.
    for (int i = 0; i <= 5; i++)
  • C.
    for (int i = 1; i <= 5; i++)
  • D.
    for (int i = 5; i >= 1; i++)

Answer: C
Starts at 1 and includes 5 → classic counting loop.

Question 8

What is printed?

int x = 10;

if (x > 5)
    if (x < 8)
        System.out.println("A");
    else
        System.out.println("B");
  • A. A
  • B. B
  • C. Nothing
  • D. Compile-time error

Answer: B
The else pairs with the nearest unmatched if.

Question 9

What is the output?

int sum = 0;

for (int i = 1; i <= 4; i++) {
    sum += i;
}

System.out.println(sum);
  • A. 6
  • B. 10
  • C. 12
  • D. 16

Answer: B
Accumulator pattern: 1 + 2 + 3 + 4 = 10.

Question 10

Which statement about loops is TRUE?

  • A. A while loop always runs at least once.
  • B. A for loop cannot be infinite.
  • C. Loop variables must be declared outside the loop.
  • D. A loop must eventually make its condition false.

Answer: D
Every correct loop must change state so its condition eventually becomes false.

Unit 2 Practice Exam MCQ/FRQ and Answers

🚀 Next Steps: Move on to Unit 3 — Class Creation

Once you're comfortable with loops, boolean logic, and String traversal, you're ready for Unit 3: Class Creation, where you'll learn how to design your own classes, write constructors, and define methods.

Continue your AP CSA path here:
Continue to AP CSA Unit 3: Class Creation →

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

tanner@apcsexamprep.com

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at tanner@apcsexamprep.com