| Learning Objective | Essential Knowledge |
|---|---|
2.1.A |
|
Selection and Iteration
7:57
Selection and Iteration
Here are three loops. The first two differ by one character — a less-than instead of a less-than-or-equal. The first runs ten times. The second runs eleven.…
English narration · English and 中文 subtitles you can switch
2.1
Selection and Repetition in Algorithms
Syllabus
Source: College Board AP Course and Exam Description
Why it matters. On 31 December 2008, thousands of Microsoft Zune 30 GB music players froze at the same moment. Their clock code used a while loop that subtracted 365 or 366 days a year from a day count. On day 366 of a leap year, neither branch of the if inside the loop changed the count, so the loop never ended. The players worked again the next day, when the count moved on. One boundary condition in one loop - exactly the kind of selection and iteration logic this unit teaches you to trace.
Algorithms 算法 are built from three control structures 控制结构: sequence 顺序 (steps in order), selection 选择 (choosing a path), and iteration 迭代 (repeating steps). This topic covers selection and iteration – the tools that let a program make decisions and loop.

| English |
|---|
| Algorithms/ˈælɡərɪθəmz/ |
| control structures/kənˈtrəʊl ˈstrʌktʃəz/ |
| sequence/ˈsiːkwəns/ |
| selection/sɪˈlekʃn/ |
| iteration/ˌɪtəˈreɪʃn/ |
2.2
Boolean Expressions
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.2.A |
|
Source: College Board AP Course and Exam Description
A boolean expression 布尔表达式 evaluates to true or false, using relational operators 关系运算符: == (equal), != (not equal), <, >, <=, >=. Note == compares primitive values 基本类型值 but object references 对象引用 for objects, so use .equals for Strings.
Worked example. With int a = 7, b = 3; and String s = "cat";:
| Expression | Value | Why |
|---|---|---|
a % b == 1 |
true |
7 % 3 is 1 |
a / b >= 2.5 |
false |
7 / 3 is the int 2 |
a != b * 2 |
true |
b * 2 is 6; arithmetic runs before comparing |
s.equals("cat") |
true |
same characters |
s.length() > b |
false |
3 > 3 is false |
A common mistake is = for ==: if (a = 7) does not compile, because = assigns and gives an int, not a boolean.

Explore the AND truth table
A Boolean expression evaluates to true or false. AND is true only when both operands are true; toggle the inputs to see all four cases.
| English |
|---|
| boolean expression/ˈbuːlɪən ekˈspreʃn/ |
| relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/ |
| primitive values/ˈprɪmɪtɪv ˈvæljuːz/ |
| object references/ˈɒbdʒekt ˈrefrənsɪz/ |
2.3
The if Statement
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.3.A |
|
Source: College Board AP Course and Exam Description
An if statement 条件语句 runs a block 代码块 only when its condition 条件 is true; an optional else gives an alternative:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

Common mistakes.
- A semicolon after the condition ends the
if: inif (x > 0); { count++; }the block runs every time. - Without braces only one statement belongs to the
if. Below,"Done"prints whatevertis, despite the indentation:
if (t > 30)
System.out.println("Hot");
System.out.println("Done");
See which branch an if chooses
An if statement runs its body only when the condition is true, otherwise it skips to else. Slide the score across the boundaries and watch the grade change.
| English |
|---|
| if statement/ɪf ˈsteɪtmənt/ |
| condition/kənˈdɪʃn/ |
| block/blɒk/ |
2.4
Nested if Statements
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.4.A |
|
Source: College Board AP Course and Exam Description
Placing an if inside another, or chaining with else if, tests several cases in order. Only the first matching branch 分支 runs:
if (g >= 90) grade = 'A';
else if (g >= 80) grade = 'B';
else grade = 'C';
Worked example. The order of the tests matters. This version never gives an 'A':
if (g >= 80) grade = 'B';
else if (g >= 90) grade = 'A'; // never reached for g >= 90
else grade = 'C';
For g = 95 the first test is already true, so 'B' is chosen and the rest is skipped. With ranges, test the narrowest case first (highest mark first), as in the correct version above. If the chain used separate if statements without else, every true test would run and the last one would win.
| English |
|---|
| branch/bræntʃ/ |
2.5
Compound Boolean Expressions
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.5.A |
|
Source: College Board AP Course and Exam Description
Logical operators 逻辑运算符 combine conditions: && (and – both true), || (or – at least one true), ! (not – reverse). Java uses short-circuit evaluation 短路求值: && stops if the left side is false, and || stops if the left side is true – useful to guard against 防止 errors, e.g. if (n != 0 && total / n > 5).

Worked example. Evaluate !(x > y) || x < 5 && y == 6 for x = 4, y = 6. The order is !, then &&, then ||:
x > yis4 > 6, false, so!(x > y)is true.x < 5 && y == 6istrue && true, true.true || trueis true. In fact, step 2 is never run:||already hastrueon its left and short-circuits.
Short-circuiting changes what runs. In if (s != null && s.length() > 0) the null check must come first; the other order throws a NullPointerException when s is null.
| English |
|---|
| Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/ |
| short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/ |
| guard against/ɡɑːd əˈɡenst/ |
| null/nʌl/ |
2.6
Comparing Boolean Expressions
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.6.A |
|
2.6.B |
|
Source: College Board AP Course and Exam Description
De Morgan's laws 德摩根定律 rewrite negations: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Two boolean expressions are equivalent 等价 if they give the same result for every input – a truth table 真值表 proves it. Simplifying conditions this way is a common exam task.
Worked example. Write !(age >= 13 && age <= 19) without the !.
- De Morgan:
!(age >= 13) || !(age <= 19)(the&&becomes||). - Negate each comparison:
!(age >= 13)isage < 13;!(age <= 19)isage > 19. - Result:
age < 13 || age > 19, every age outside the teens.
Check one value of each kind: age = 15 gives false in both; age = 25 gives true in both. A common error is to negate >= as <=: the opposite of >= is <.
a |
b |
!(a && b) |
!a || !b |
|---|---|---|---|
| T | T | F | F |
| T | F | T | T |
| F | T | T | T |
| F | F | T | T |
Comparing object references
For objects, == and != compare references 引用, not contents: a == b is true only when a and b refer to the same object. Two variables that refer to the same object are aliases 别名.
String s1 = new String("cat");
String s2 = new String("cat");
String s3 = s1;
System.out.println(s1 == s2); // false: two different objects
System.out.println(s1 == s3); // true: s3 is an alias of s1
System.out.println(s1.equals(s2)); // true: same characters
A reference that does not refer to any object holds null 空值. Test for it with == or != before calling a method, because calling a method on null throws a NullPointerException:
if (name != null && name.equals("Ana")) // safe if name is null
Many classes define their own equals method, which decides when two objects count as equal, usually by comparing their attributes (instance variables). String's equals compares the characters. A class that does not define one uses the Object version, which works like ==. (You will not be asked to write an equals method.)
Worked example. The Point class has an equals method that compares x and y. Evaluate p == q, q == r and p.equals(q) after this code:
Point p = new Point(2, 3);
Point q = new Point(2, 3);
Point r = q;
p and q were made by two separate new calls, so they are two objects: p == q is false. r = q copies the reference, so r and q are aliases: q == r is true. equals compares the attributes, which are both $(2, 3)$: p.equals(q) is true. If q.setX(5) is then called, r.getX() also returns 5, because r is the same object.

One matching row is not enough
Compare the original, De Morgan rewrite and unflipped candidate for every pair of pure Boolean inputs. A mismatch is a counterexample.
| English |
|---|
| De Morgan's laws/də ˈmɔːɡənz lɔːz/ |
| equivalent/ɪˈkwɪvələnt/ |
| truth table/truːθ ˈteɪbl/ |
| reference/ˈrefrəns/ |
| aliases/ˈeɪlɪəsɪz/ |
2.7
while Loops
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.7.A |
|
2.7.B |
|
Source: College Board AP Course and Exam Description
A while loop 当型循环 repeats while its condition stays true, testing before each pass. You must change something inside so the loop eventually stops, or it becomes an infinite loop 无限循环:

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Worked example. Trace a loop that adds the digits of n = 472:
int n = 472, sum = 0;
while (n > 0) {
sum += n % 10; // last digit
n /= 10; // drop it
}
| Pass | n % 10 |
sum |
n after |
|---|---|---|---|
| 1 | 2 | 2 | 47 |
| 2 | 7 | 9 | 4 |
| 3 | 4 | 13 | 0 |
After pass 3 the test n > 0 is false, so the loop stops with sum = 13. If n started at 0, the body would run zero times: a while loop tests before the first pass.
Trace a while loop
A while loop repeats as long as its condition stays true, updating its variables each pass. Step through to see the sum of squares build up.
| English |
|---|
| while loop/waɪl luːp/ |
| infinite loop/ˈɪnfɪnət luːp/ |
2.8
for Loops
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.8.A |
|
Source: College Board AP Course and Exam Description
A for loop packs initialization 初始化, condition, and update 更新 into one line – best when you know the count:
for (int i = 0; i < n; i++) {
// runs n times, i = 0..n-1
}
A for and an equivalent while do the same work; be able to convert between them.
Worked example. How many times does this run, and what does it print?
for (int k = 10; k > 0; k -= 3)
System.out.print(k + " ");
k takes the values 10, 7, 4, 1; the next value, $-2$, fails k > 0. So it runs 4 times and prints 10 7 4 1. The equivalent while moves the three parts apart:
int k = 10;
while (k > 0) {
System.out.print(k + " ");
k -= 3;
}
A loop for (int i = a; i < b; i++) runs $b - a$ times; with <= it runs $b - a + 1$ times. A variable declared in the for header, such as k, cannot be used after the loop.


Trace a for loop
A for loop runs a fixed number of times, its counter stepping through a range. Watch the counter and running total advance one pass at a time.
| English |
|---|
| initialization/ɪˌnɪʃəlaɪˈzeɪʃn/ |
| update/ˈʌpdeɪt/ |
2.9
Building Complete Selection and Iteration Algorithms
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.9.A |
|
Source: College Board AP Course and Exam Description
Combine loops and conditions to solve real problems – count, sum, find a maximum, or test a property:
int max = arr[0];
for (int k = 1; k < arr.length; k++) {
if (arr[k] > max) max = arr[k];
}
Two integer patterns the exam tests directly use % and /. For a nonnegative integer 整数 n, read its digits 数字位 one at a time by taking n % 10 (the last digit) and then n = n / 10 (drop it). For nonzero d, n % d == 0 tests divisibility 整除性: n is evenly divisible by d. Combine them with a counter 计数器 to find the frequency 频率 with which some criterion 条件标准 is met.
Worked example. Count the numbers from 1 to 20 that are divisible by 3 but not by 2.
int count = 0;
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0 && i % 2 != 0) {
count++;
}
}
The multiples of 3 are 3, 6, 9, 12, 15, 18; the odd ones are 3, 9, 15, so count is 3. The counter starts at 0 before the loop; resetting it inside the loop is a common error.

Standard patterns like a running total 累加和, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.
| English |
|---|
| integer/ˈɪntɪdʒə/ |
| digits/ˈdɪdʒɪts/ |
| divisibility/dɪˌvɪzɪˈbɪlɪti/ |
| counter/ˈkaʊntə/ |
| frequency/ˈfriːkwənsi/ |
| criterion/kraɪˈtɪərɪən/ |
| running total/ˈrʌnɪŋ ˈtəʊtl/ |
| flag/flæɡ/ |
2.10
String Algorithms
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.10.A |
|
Source: College Board AP Course and Exam Description
Loop through a string by index 索引 to process each character 字符:
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// count vowels, reverse, check for a substring, ...
}
Typical tasks: count occurrences 出现次数, build a reversed or filtered copy, or test whether one string contains another.
Worked example. Count how many times "ana" occurs in "banana", overlaps included.
String s = "banana", t = "ana";
int count = 0;
for (int i = 0; i <= s.length() - t.length(); i++) {
if (s.substring(i, i + t.length()).equals(t)) {
count++;
}
}
i runs from 0 to $6 - 3 = 3$, checking "ban", "ana", "nan", "ana": count is 2. With i < s.length() instead, substring(4, 7) is past the end and throws a StringIndexOutOfBoundsException.

| English |
|---|
| index/ˈɪndeks/ |
| character/ˈkærɪktə/ |
| occurrences/əˈkɜːrənsɪz/ |
2.11
Nested Iteration
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.11.A |
|
Source: College Board AP Course and Exam Description
A nested loop 嵌套循环 puts one loop inside another; the inner loop 内层循环 completes fully for each pass of the outer loop 外层循环. If the outer runs $n$ times and the inner $m$ times, the body runs $n\times m$ times – the basis for processing grids 网格 and comparing all pairs.

Worked example. What does this print?
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= r; c++) {
System.out.print(c);
}
System.out.println();
}
r |
c takes |
Line printed |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1, 2 | 12 |
| 3 | 1, 2, 3 | 123 |
The println is inside the outer loop but outside the inner one, so it ends each row.
| English |
|---|
| nested loop/ˈnestɪd luːp/ |
| inner loop/ˈɪnə luːp/ |
| outer loop/ˈaʊtə luːp/ |
| grids/ɡrɪdz/ |
2.12
Informal Run-Time Analysis
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
2.12.A |
|
Source: College Board AP Course and Exam Description
Run-time analysis 运行时间分析 counts how many basic steps an algorithm takes as the input size $n$ grows. Count the executions of the innermost statement: with constant work per iteration, visiting each of $n$ items once is linear 线性 ($n$ steps); two full nested loops of $n$ iterations each are quadratic 平方级 ($n^2$). This informal counting lets you compare two algorithms' efficiency 效率.

Exam skill: for a nested loop, be able to state how many times the inner statement runs in terms of the loop bounds – a frequent multiple-choice question.
Worked example. How many stars does this print?
for (int i = 0; i < 4; i++)
for (int j = 0; j < i; j++)
System.out.print("*");
The inner loop runs i times for each outer i: 0 + 1 + 2 + 3 = 6 stars. When the inner bound is the outer variable, the total is the triangular sum $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ – here $\dfrac{4\times3}{2}=6$ – not the full $n^2=16$ of a rectangular nested loop.
Compare how algorithms scale
Run-time describes how the number of steps grows with the input size $n$. Increase $n$ and watch a linear $O(n)$ pull far ahead of a quadratic $O(n^2)$.
| English |
|---|
| Run-time analysis/rʌn taɪm əˈnæləsɪs/ |
| linear/ˈlɪnɪə/ |
| quadratic/kwɒˈdrætɪk/ |
| efficiency/ɪˈfɪʃənsi/ |
2.12
Exam tips
- Get boundary conditions 边界条件 right: use
<vs<=deliberately, and watch the first and last iteration of every loop (off-by-one 差一错误 is the classic bug 缺陷). - Build compound conditions with
&&,||,!and remember short-circuit evaluation (put the null check first). - Trace nested loops by counting how many times the inner body runs in total.
- Choose the right structure —
if/else iffor ranges, a loop for repetition — and avoid an infinite loop by updating the loop variable 循环变量. - Apply De Morgan's laws when you simplify or negate a boolean condition.
Common mistakes (whole unit).
- Writing
if (x = 5)instead ofif (x == 5). In Java this does not compile for anint, but the habit causes errors elsewhere. - Putting a semicolon after the condition:
if (x > 0);ends theifthere, so the next block always runs. - Looping with
i <= s.length(), which reaches an index one past the end and throws aStringIndexOutOfBoundsException. - Comparing strings with
==instead of.equals(...).==asks whether two references point to the same object;equalsasks whether the contents match. - Calling a method on a reference before checking it is not
null. Put the!= nulltest first in an&&. - Forgetting to update the loop variable in a
whileloop, making an infinite loop.
Practice.
- Why is
if (s != null && s.length() > 0)safe, butif (s.length() > 0 && s != null)not? - Use De Morgan's laws to rewrite
!(x < 3 || y >= 5)without!. - How many times does
for (int i = 3; i <= 15; i += 4)run? - What is
nafter this code runs?int n = 1; while (n < 100) { n *= 3; } - Write a code segment that counts the vowels (a, e, i, o, u) in a lowercase
String word. - How many times does the inner body run?
for (int i = 0; i < 4; i++) { for (int j = 0; j < i; j++) { ... } }
Answers.
-
&&short-circuits: ifsisnullthe second test is never evaluated. In the second versions.length()runs first and throws aNullPointerException. -
x >= 3 && y < 5. -
Four times (
i= 3, 7, 11, 15). -
243(1, 3, 9, 27, 81, 243; the loop stops whennis no longer below 100). -
One answer:
int count = 0; for (int i = 0; i < word.length(); i++) { String c = word.substring(i, i + 1); if ("aeiou".indexOf(c) >= 0) { count++; } } -
$0 + 1 + 2 + 3 = 6$ times.
| English |
|---|
| boundary conditions/ˈbaʊndəri kənˈdɪʃnz/ |
| off-by-one/ɒf baɪ wʌn/ |
| bug/bʌɡ/ |
| loop variable/luːp ˈveərɪəbl/ |
What went wrong? Only the site team sees this.
Interactive lessons on this topic
Work through it step by step, with instant-check exercises.