AP CSA Unit 2: Selection and Iteration - Ultimate Study Guide

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.

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

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

🔀 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

🔁 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

🔂 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
}
💡 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:
*
**
***
****
*****
*/
📝 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.

📝 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 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");
}
Answer: A
Both conditions (x > 5 and x < 10) are true when x = 7, so the compound condition is true.

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++;
    }
}
Answer: B
Numbers divisible by 3 between 1 and 10 are: 3, 6, and 9 (three numbers).

Question 3

What is printed?

int x = 0;
if (x != 0 && 10 / x > 1) {
    System.out.println("Yes");
} else {
    System.out.println("No");
}
Answer: B
Short-circuit evaluation: x != 0 is false, so 10 / x is never evaluated. No error occurs.

Question 4

How many times does "X" print?

for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.print("X");
    }
}
Answer: B
Outer runs 4 times, inner runs 3 times each → 4 × 3 = 12.

Question 5

Which expression is equivalent to !(a && b) using De Morgan's Law?

Answer: B
By De Morgan's Law: !(A && B) = !A || !B. The AND flips to OR.

Question 6

What is printed?

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
System.out.println(sum);
Answer: B
Accumulator pattern: 1 + 2 + 3 + 4 + 5 = 15.

📋 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;
}

AP Computer Science A Unit 2 Study Guide

© 2026 AP CS Exam Prep | Good luck on your exam!

Contact form