Units 2 — Selections & Iteration
Java fundamentals through control flow: variables and methods, then Boolean logic, if statements, and loops. Each section ends with a short practice set — click "Show answer" to check yourself.
Algorithms with Selection and Repetition
Every algorithm is built from three control structures, combined in any order or nesting:
- Sequence — statements run one after another, top to bottom.
- Selection — a branch point where the program picks one path based on a condition (
if). - Repetition (iteration) — a block of code repeats while some condition holds (
while,for).
1. A program checks if a number is positive, then prints "yes" or "no". Which control structure is this?
Show answer
2. Can repetition contain selection inside it? Give a one-line example scenario.
Show answer
if to print only the even ones. Control structures nest freely.Boolean Expressions
A Boolean expression is any expression that evaluates to exactly one of two values: true or false. They're built using relational operators (== != < > <= >=) and combined with logical operators (&& || !) — see 1.16 for the full table.
boolean isTeen = (age >= 13) && (age <= 19); boolean failed = grade < 60; System.out.println(isTeen); // prints "true" or "false" directly
A Boolean expression can be stored in a boolean variable, printed directly, or used immediately as the condition of an if or a loop.
1. Is x = 5 a Boolean expression? What about x == 5?
Show answer
x = 5 is an assignment, not a Boolean expression — it doesn't evaluate to true/false. x == 5 is a Boolean expression; it evaluates to true or false depending on x's value.2. Write a Boolean expression that's true when a score is a passing grade (60 or above) but not a perfect 100.
Show answer
(score >= 60) && (score != 100)if Statements
An if statement runs a block of code only when its Boolean condition is true. Pairing it with else gives a second path when the condition is false.
if (temperature > 90) { System.out.println("It's hot"); } else { System.out.println("It's not that hot"); }
- The condition must be inside parentheses and must be a Boolean expression.
- Curly braces group multiple statements into one block; without them, only the very next single statement belongs to the
if. elseis optional — anifwith noelsesimply does nothing when the condition is false.
if (x > 0); — creates an empty statement as the "if body," so the block below always runs regardless of the condition.if (score >= 60)
System.out.println("Pass");
System.out.println("Recorded");
1. If score is 40, what prints?
Show answer
"Recorded". Without braces, only the first line belongs to the if; the second line always runs regardless of the condition.2. Write an if/else that prints "Even" or "Odd" for an int n.
Show answer
if (n % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); }Nested if Statements
Nested ifs place an if inside another if (or its else), allowing multi-way branching. else if chains are the most common pattern.
if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else { System.out.println("F"); }
- In an
else ifchain, Java checks each condition top-to-bottom and stops at the first one that's true — order matters. - A series of independent
ifstatements (noelse) all get checked, even after one is true — very different behavior from a chain.
1. Using the grade chain above, what prints for grade = 95?
Show answer
"A" — the first condition, grade >= 90, is true, so Java stops there and skips the rest of the chain.2. Why would swapping the order to check grade >= 70 first break this chain?
Show answer
Compound Boolean Expressions
Combining multiple conditions with &&, ||, and ! builds richer conditions than any single comparison can express.
boolean eligible = (age >= 16) && hasPermit && !hasViolation; if (day == "Sat" || day == "Sun") { System.out.println("Weekend"); }
| a | b | a && b | a || b |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Recall from 1.16 that && and || short-circuit — this is especially useful for guarding against errors, like checking an index is in range before using it.
1. Write a compound condition that's true when a year is a leap year: divisible by 4, but not by 100 unless also divisible by 400.
Show answer
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)2. In str != null && str.length() > 0, why must str != null come first?
Show answer
str != null is false, Java never evaluates str.length() — avoiding a crash from calling a method on null. Swapping the order would remove that protection.Comparing Boolean Expressions
Two Boolean expressions are logically equivalent if they produce the same true/false result for every possible input. De Morgan's Laws describe how negation distributes over && and ||:
| Original | Equivalent to |
|---|---|
!(a && b) | !a || !b |
!(a || b) | !a && !b |
// these two conditions are logically equivalent if (!(x > 0 && y > 0)) { ... } if (x <= 0 || y <= 0) { ... }
To verify two expressions are equivalent, build a truth table — list every combination of the input variables and check the outputs match in every row.
1. Apply De Morgan's Law to rewrite !(isRaining || isSnowing) without a leading ! over the whole expression.
Show answer
!isRaining && !isSnowing2. Are a && (b || c) and (a && b) || c logically equivalent?
Show answer
false && true = false; the second gives false || true = true. They disagree, so they're not equivalent — grouping matters.while Loops
A while loop repeats a block of code as long as its condition remains true, checking the condition before each pass. It's ideal when you don't know in advance how many times you'll loop.
int count = 0; while (count < 5) { System.out.println(count); count++; // without this, the loop never ends }
- The condition is checked before every iteration — if it's false immediately, the body never runs at all.
- Something inside the loop must eventually make the condition false, or you get an infinite loop.
whileis common for sentinel-controlled loops — e.g. keep reading input until the user types "quit."
int n = 10;
while (n > 0) {
n -= 3;
}
System.out.println(n);
1. What does this print?
Show answer
-2. n goes 10 → 7 → 4 → 1 → -2; once n is -2, n > 0 is false, so the loop stops.2. What's wrong with while (x != 10) { x += 3; } if x starts at 0?
Show answer
x != 10 is never false.for Loops
A for loop packages initialization, condition, and update into one header — ideal when you know roughly how many times you'll loop (a definite loop).
for (int i = 0; i < 5; i++) { System.out.println(i); // prints 0 1 2 3 4 }
| Part | Runs | In the example |
|---|---|---|
| Initialization | Once, before the loop starts | int i = 0 |
| Condition | Before every iteration | i < 5 |
| Update | After every iteration | i++ |
Every for loop can be rewritten as a while loop, and vice versa — for is just more compact when a counter is involved.
1. Write a for loop that prints the numbers 10 down to 1.
Show answer
for (int i = 10; i >= 1; i--) { System.out.println(i); }int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
2. What is sum after this loop?
Show answer
10 — it adds 1 + 2 + 3 + 4.Implementing Selection and Iteration Algorithms
Most algorithms combine loops with ifs using a small set of reusable patterns:
| Pattern | Idea |
|---|---|
| Accumulator | A variable that grows across iterations (running sum or product) |
| Counter | Tracks how many items met some condition |
| Max / Min tracker | Remembers the best value seen so far, updated via if |
int[] scores = {72, 95, 60, 88}; int sum = 0, passingCount = 0, max = scores[0]; for (int s : scores) { sum += s; // accumulator if (s >= 70) passingCount++; // counter if (s > max) max = s; // max tracker }
1. Why does the max tracker start at scores[0] instead of 0?
Show answer
2. Write a loop that counts how many elements of an int array arr are even.
Show answer
int count = 0; for (int x : arr) { if (x % 2 == 0) count++; }Implementing String Algorithms
Strings are iterated character-by-character using .length() and .charAt(i) inside a loop — the same accumulator patterns from 2.9 apply directly.
int vowels = 0; String s = "education"; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') { vowels++; } } // building a new string char by char String reversed = ""; for (int i = s.length() - 1; i >= 0; i--) { reversed += s.charAt(i); }
reversed += s.charAt(i) creates a brand-new String each pass, it doesn't mutate one in place.1. Write a loop condition that checks whether a String word is a palindrome (reads the same forwards and backwards).
Show answer
boolean isPal = word.equals(reversed); after building reversed as shown above — or compare word.charAt(i) with word.charAt(word.length()-1-i) for each i up to the midpoint.2. What does the vowel-counting loop above return for "education"?
Show answer
5 — e, u, a, i, o are all present.Nested Iteration
A loop placed inside another loop is nested iteration. For each single pass of the outer loop, the entire inner loop runs to completion.
for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { System.out.print(row * col + " "); } System.out.println(); // new line after each row } // prints a 3x3 multiplication grid
The outer loop runs 3 times; for each of those, the inner loop runs 3 times — so the inner body executes 3 × 3 = 9 times total. This multiplying effect is the key idea behind nested loops.
1. How many total times does the innermost line run in a nested loop where the outer runs 4 times and the inner runs 6 times each pass?
Show answer
24 times (4 × 6).2. Write nested loops that print a 5-row triangle of asterisks (row 1 has one *, row 5 has five).
Show answer
for (int row = 1; row <= 5; row++) { for (int c = 1; c <= row; c++) { System.out.print("*"); } System.out.println(); }Informal Run-Time Analysis
Run-time analysis asks: as the input size n grows, how does the number of operations grow? This is described informally with Big-O notation.
| Pattern | Growth | Example |
|---|---|---|
| No loop | O(1) — constant | A fixed number of statements |
| Single loop over n items | O(n) — linear | Summing an array of size n |
| Nested loop, both over n | O(n²) — quadratic | Comparing every pair in a list |
// O(n) — one pass through the array for (int x : arr) { sum += x; } // O(n^2) — inner loop re-scans for every outer element for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { // n x n work } }
1. A loop runs from 0 to n, and inside it, a second independent loop also runs from 0 to n. What's the informal run time?
Show answer
2. Is printing the first element of an array, regardless of the array's size, O(1) or O(n)?