Summer Camp 2026 — Enroll Now APCSA & APCSP Prep Classes Starting June Learn Python, Java & Web Design AP Cybersecurity — New Course Starting from 2026 Expert-Led · Small Batches · Hands-On Projects Contact: oggntech@gmail.com Summer Camp 2026 — Enroll Now APCSA & APCSP Prep Classes Starting June Learn Python, Java & Web Design AP Cybersecurity — New Course Starting from 2026 Expert-Led · Small Batches · Hands-On Projects Contact: oggntech@gmail.com
Study Notes

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.

2.1

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).
Big picture: Unit 1 was mostly sequence. Unit 2 adds selection and repetition — with just these three tools, you can express any algorithm.
Practice

1. A program checks if a number is positive, then prints "yes" or "no". Which control structure is this?

Show answer
Selection — the program branches based on a condition.

2. Can repetition contain selection inside it? Give a one-line example scenario.

Show answer
Yes — e.g. looping through a list of numbers and, inside the loop, using an if to print only the even ones. Control structures nest freely.
2.2

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.

Practice

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)
2.3

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.
  • else is optional — an if with no else simply does nothing when the condition is false.
Common bug: a stray semicolon after the condition — if (x > 0); — creates an empty statement as the "if body," so the block below always runs regardless of the condition.
Practice
if (score >= 60)
    System.out.println("Pass");
    System.out.println("Recorded");

1. If score is 40, what prints?

Show answer
Only "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"); }
2.4

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 if chain, Java checks each condition top-to-bottom and stops at the first one that's true — order matters.
  • A series of independent if statements (no else) all get checked, even after one is true — very different behavior from a chain.
Order matters: writing the 80-cutoff check before the 90-cutoff check would mean a 95 never reaches the "A" branch, since 95 also satisfies >= 80.
Practice

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
Any grade of 70 or above (including 85s and 95s) would immediately satisfy that first, loosest condition and get labeled "C," since the chain stops at the first true condition.
2.5

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");
}
aba && ba || b
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

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.

Practice

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
Short-circuiting means if 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.
2.6

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 ||:

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

Practice

1. Apply De Morgan's Law to rewrite !(isRaining || isSnowing) without a leading ! over the whole expression.

Show answer
!isRaining && !isSnowing

2. Are a && (b || c) and (a && b) || c logically equivalent?

Show answer
No. Test a=false, b=false, c=true: the first gives false && true = false; the second gives false || true = true. They disagree, so they're not equivalent — grouping matters.
2.7

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.
  • while is common for sentinel-controlled loops — e.g. keep reading input until the user types "quit."
Practice
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
It's an infinite loop: x goes 0, 3, 6, 9, 12, 15... and skips over 10 entirely, so x != 10 is never false.
2.8

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
}
PartRunsIn the example
InitializationOnce, before the loop startsint i = 0
ConditionBefore every iterationi < 5
UpdateAfter every iterationi++

Every for loop can be rewritten as a while loop, and vice versa — for is just more compact when a counter is involved.

Practice

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

Implementing Selection and Iteration Algorithms

Most algorithms combine loops with ifs using a small set of reusable patterns:

PatternIdea
AccumulatorA variable that grows across iterations (running sum or product)
CounterTracks how many items met some condition
Max / Min trackerRemembers 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
}
Initialize carefully: a sum starts at 0, a product starts at 1, and a max tracker should start at the first element (not 0 — real data can be negative).
Practice

1. Why does the max tracker start at scores[0] instead of 0?

Show answer
If every score were negative, starting at 0 would incorrectly "win" over all of them. Starting from an actual element in the data avoids that bug.

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++; }
2.10

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);
}
Remember: Strings are immutable (1.15) — reversed += s.charAt(i) creates a brand-new String each pass, it doesn't mutate one in place.
Practice

1. Write a loop condition that checks whether a String word is a palindrome (reads the same forwards and backwards).

Show answer
One approach: 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.
2.11

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.

Practice

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(); }
2.12

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.

PatternGrowthExample
No loopO(1) — constantA fixed number of statements
Single loop over n itemsO(n) — linearSumming an array of size n
Nested loop, both over nO(n²) — quadraticComparing 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
    }
}
Informal, not exact: at this level, run-time analysis is about the general shape of growth (constant vs. linear vs. quadratic), not a precise formula — that level of rigor comes later.
Practice

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
O(n²) — the inner loop's full n iterations happen for every one of the outer loop's n iterations.

2. Is printing the first element of an array, regardless of the array's size, O(1) or O(n)?

Show answer
O(1) — it's a single fixed operation with no loop, so it takes the same amount of work no matter how large the array is.