AP CSA Unit 2 Study Guide 2026 | Selection & Iteration
AP CSA Study Guides
AP CSA Unit 2 Study Guide | 2025-2026
AP CSA Unit 2 Study Guide 2026 | Selection & Iteration
AP Computer Science A
Complete Study Guide — 2025-2026 Curriculum
📚 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.
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 |
== 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
.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!)
🔄 De Morgan's Law
De Morgan's Law provides rules for distributing a NOT operator over AND and OR expressions.
The Two Rules
NOT (A AND B) equals (NOT A) OR (NOT 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");
}
🔀 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
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++; |
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;
}| Check # | n before | n ≤ 16? | Action | n after |
|---|
🔂 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
- Initialization executes ONCE at the very beginning
- Condition is checked BEFORE each iteration
- If condition is true, the loop body executes
- Update executes AFTER each iteration of the body
- 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;
}| Step | Phase | i | sum | i < 5? | Action |
|---|
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)
}
}Total iterations = 3 × 4 = 12. Multiply outer × inner loop counts.
📈 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);
📈 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);
✓ Count / Tally
int count = 0;
for (String s : words) {
if (s.length() > 5) {
count++;
}
}
System.out.println(count);
🔍 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");
}
🔄 Running Product
int product = 1; // initialize to 1, NOT 0
for (int x : arr) {
product *= x;
}
System.out.println(product);
📝 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);
On FRQ Q1, underline the output type (int, String, boolean, void) before writing any code. That tells you which pattern to use:
- Returns
intwith a numeric result → Sum, Max, or Count pattern - Returns
intthat could be -1 → Linear Search pattern - Returns
Stringbuilt from input → String Builder pattern - Returns
boolean→ often a search with early returntrue, returnfalseafter 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");
}
{} with if statements and loops, even for single-line bodies. This prevents many common bugs.
✍ Practice Questions
These questions match actual AP exam difficulty. Predict your answer before reading the options. 15 questions covering all Unit 2 topics.
int count = 1;
while (count <= 10) {
System.out.print(count + " ");
count++;
}
1: int total = 0;
2: for (int k = 1; k <= 5; k++);
3: {
4: total += k;
5: }
6: System.out.println(total);
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.System.out.println() execute?for (int i = 0; i < 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.println(i + " " + j);
}
}
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})
n after this loop completes?int n = 1;
while (n <= 100) {
n *= 2;
}
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.!(p || q) equal to true, where p is x > 3 and q is y < 10?{1, 2, 3, 4}?public static int firstEven(int[] arr) {
for (int val : arr) {
if (val % 2 == 0) {
return val;
}
}
return -1;
}
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;
}
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++)
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");
}
{1,2,3,4,5}.public static int doubleSum(int[] arr) {
for (int val : arr) {
int result = 0;
result += val * 2;
}
return result;
}
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.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;
}
Finished Unit 2? Here is What to Do Next.
Take the Unit 2 Practice Exam
Test yourself on everything you just studied. Instant scoring and explanations.
💻Write Real Code (Interactive)
FRQ-style practice with a live Java editor and auto-grading.
📝Practice Real FRQs
Every AP CSA FRQ from 2004–2025 with full solutions and scoring guides.
⚙Build a Custom Test
586 questions. Filter by unit and topic. Create your own practice exam.
Need a Structured Study Plan?
The 4-Week Cram Kit gives you a day-by-day plan covering every unit — with daily drills and FRQ practice.
Get the Cram Kit — $29.99 Book 1-on-1 TutoringDaily Practice Questions
Free daily MCQs covering all 4 units. New question every day through May 15.
🎮21 Interactive Study Games
Jeopardy, crosswords, memory match, and more. Learn while you play.
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]