AP CSA Unit 2 Notes: Mastering Selection and Iteration in Java
Building Boolean Conditions in Java
Selection (making decisions) and iteration (repeating work) both rely on the same foundation: boolean expressions. A boolean expression is any expression that evaluates to either true or false. In Java, these expressions drive if statements and loop conditions—so if you can read and write boolean expressions confidently, the rest of the unit becomes much easier.
What makes something boolean?
A value is boolean if its type is boolean or if it’s an expression that produces a boolean result. Common sources:
- Relational comparisons between numbers/characters:
<,<=,>,>= - Equality comparisons:
==,!= - Logical operators combining booleans:
&&,||,! - Boolean variables or method calls returning boolean (for example,
someString.equals("hi"))
A key idea: Java is not like some languages where numbers can stand in for booleans. In Java, the condition in an if or while must be a boolean expression—if (x) is illegal if x is an int.
Relational operators (ordering comparisons)
Use relational operators when you care about ordering:
a < bmeans “a is less than b”a >= bmeans “a is greater than or equal to b”
These operators work naturally with numeric primitives (int, double) and also with char (because chars have numeric Unicode values). For AP CSA, you should be comfortable comparing int and double values and interpreting the result.
Be careful when comparing double values—because floating-point values can have rounding issues, exact equality comparisons can be unreliable. The AP exam typically avoids tricky floating-point precision traps, but it’s still good practice to avoid relying on == for doubles in real-world code.
Equality operators (same vs different)
The operators:
==checks equality!=checks inequality
For primitive types (int, double, char, boolean), == compares the actual values.
For objects (like String), == compares whether two references point to the same object in memory, not whether the objects have the same contents. This is such a common source of bugs that AP CSA expects you to know the difference (we’ll treat this carefully in a dedicated section).
Logical operators (combining conditions)
Logical operators let you build more expressive conditions:
- AND:
p && qistrueonly if bothpandqaretrue. - OR:
p || qistrueif at least one ofporqistrue. - NOT:
!pflipstruetofalseandfalsetotrue.
These are the tools you use when one simple comparison isn’t enough—like checking that a number is within a range.
Operator precedence (how Java groups your logic)
When an expression has multiple operators, Java follows precedence rules. The most important ones here:
!happens first- Relational operators like
<and>= - Equality operators
==and!= &&||
Even if you memorize precedence, you should still use parentheses when your intent could be unclear. Parentheses reduce mistakes and make code easier to read.
Seeing boolean expressions in action
Here are a few examples and what they mean:
int x = 7;
boolean a = (x > 0); // true: x is positive
boolean b = (x % 2 == 0); // false: x is odd
boolean c = (x >= 1 && x <= 10); // true: x is in the range 1..10
boolean d = !(x == 7); // false: NOT (x equals 7)
Notice how parentheses clarify meaning. They’re not always required, but they prevent you from accidentally relying on precedence incorrectly.
Exam Focus
- Typical question patterns:
- Evaluate/tracing: “What is the value of this boolean expression given these variable values?”
- Range logic: “Which condition correctly checks if
xis betweenaandb?” - Precedence: “Which expressions are equivalent?” (often involving
!,&&,||)
- Common mistakes:
- Using
=instead of==in conditions (assignment vs comparison). - Forgetting parentheses and misreading precedence, especially with
!and mixed&&/||. - Trying to use non-boolean values as conditions (for example,
if (x)whenxis anint).
- Using
Decision-Making with if, if-else, and else-if Chains
An if statement lets your program choose between different paths. Without selection, a program is basically a fixed script: it always executes the same steps. With selection, your code can respond to input, random events, or changing state.
The basic if statement
An if statement runs a block only when its condition is true:
if (condition) {
// runs only if condition is true
}
If the condition is false, Java skips the block.
Why this matters: this is the core of “guarding” code. You can prevent invalid actions, like dividing by zero or accessing an out-of-range index (later units), by checking conditions first.
if-else: two mutually exclusive paths
Use if-else when exactly one of two blocks should run:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
This structure guarantees one branch executes. That guarantee is useful when you want to ensure a variable gets assigned:
int fee;
if (age < 12) {
fee = 5;
} else {
fee = 10;
}
// fee is definitely assigned here
else-if chains: multiple exclusive cases
An else-if chain tests conditions in order. The first true condition “wins,” and the rest are skipped.
if (temp < 32) {
System.out.println("Freezing");
} else if (temp < 60) {
System.out.println("Cold");
} else if (temp < 80) {
System.out.println("Warm");
} else {
System.out.println("Hot");
}
How it works step by step:
- Check
temp < 32. If true, print and stop. - Otherwise check
temp < 60, and so on. - If none are true, the final
elseruns (if present).
A common design tip: order your conditions from most specific to most general (or from smallest ranges upward, like above). If you put a broad condition first, it can “steal” cases that should have matched later.
Nested if statements
Nesting means putting an if inside another if.
This is useful when one decision depends on another, or when you want to avoid checking a secondary condition unless a primary condition is true.
if (hasTicket) {
if (age < 13) {
System.out.println("Child admission");
} else {
System.out.println("Regular admission");
}
} else {
System.out.println("No entry");
}
Even though nesting is sometimes necessary, deep nesting can become hard to read. Often, you can simplify by combining conditions with &&:
if (hasTicket && age < 13) {
System.out.println("Child admission");
}
But note: combining conditions only works when the logic truly matches. Nesting can represent more complex “tree” decisions.
The “dangling else” problem (how Java matches else)
In Java, an else always matches the closest preceding unmatched if. This can surprise you if you omit braces.
Bad style (easy to misread):
if (a > 0)
if (b > 0)
System.out.println("Both positive");
else
System.out.println("a is not positive?");
That else actually belongs to if (b > 0), not if (a > 0).
Best practice: always use braces for if statements in AP-level work unless the code is extremely simple and unambiguous.
Worked example: grading logic
Suppose you want:
- 90+ → A
- 80–89 → B
- 70–79 → C
- 60–69 → D
- below 60 → F
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 70) {
System.out.println("C");
} else if (score >= 60) {
System.out.println("D");
} else {
System.out.println("F");
}
Notice we check from highest downward. If we checked score >= 60 first, almost everything would print “D” and the later checks would never run.
Exam Focus
- Typical question patterns:
- Trace an
if-else if-elsechain and determine what prints. - Identify equivalent code: rewrite a nested
ifas a combined condition (or vice versa). - Reason about unreachable branches based on condition order.
- Trace an
- Common mistakes:
- Putting conditions in the wrong order so earlier cases “capture” later ones.
- Missing braces leading to an
elseattaching to the wrongif. - Using multiple separate
ifstatements when anelse-ifchain is needed (leading to multiple branches executing).
Using and Comparing Strings Correctly in Conditions
In AP CSA, String is the most important object type you work with early. Selection often depends on comparing text: commands, names, menu choices, and so on. The tricky part is that Strings are objects, and comparing objects has rules that differ from comparing primitives.
Reference vs value: what a String variable really holds
A variable of type String does not store the characters directly. It stores a reference to a String object.
That distinction matters because:
==compares references (whether two variables point to the same object)..equals(...)compares contents (whether the characters are the same).
.equals for content equality
Use .equals when you want to know if two strings have the same sequence of characters.
String s = "yes";
if (s.equals("yes")) {
System.out.println("Confirmed");
}
This is the standard AP CSA expectation: string content comparison uses .equals.
A common real bug: If you accidentally write if (s == "yes"), it might sometimes appear to work (because of string interning rules in Java), but it is not reliable and is considered incorrect reasoning for AP.
Avoiding NullPointerException
If a String variable might be null, calling s.equals("yes") will crash with a NullPointerException.
A safer pattern is to call .equals on the constant:
if ("yes".equals(s)) {
System.out.println("Confirmed");
}
This works even when s is null, because the string literal is not null.
You don’t always need this on AP-style questions (they often avoid null), but it’s a strong habit and demonstrates correct understanding.
Lexicographic comparisons with compareTo
Sometimes you want alphabetical ordering rather than equality. String.compareTo(other) returns:
- a negative number if
thiscomes beforeother - zero if they are equal
- a positive number if
thiscomes afterother
Example:
String a = "apple";
String b = "banana";
if (a.compareTo(b) < 0) {
System.out.println("a comes first");
}
A common confusion: compareTo does not return only -1, 0, or 1. It can return many possible negative or positive integers. For conditions, you should check < 0, == 0, or > 0.
Worked example: command selection
Imagine a simple text command system:
String cmd = "quit";
if (cmd.equals("help")) {
System.out.println("Showing help...");
} else if (cmd.equals("quit")) {
System.out.println("Goodbye!");
} else {
System.out.println("Unknown command");
}
This is a realistic way selection appears in programs: a value (often user input) determines which branch runs.
Exam Focus
- Typical question patterns:
- Determine whether
==or.equalsis correct in a given situation. - Trace code involving
Stringcomparisons insideifstatements. - Use
compareToresults in a condition (< 0,> 0,== 0).
- Determine whether
- Common mistakes:
- Using
==to compare string contents. - Misinterpreting
compareToas returning only-1,0,1. - Calling
.equalson a potentiallynullreference (leading toNullPointerException).
- Using
Writing Clear Compound Conditions (and Short-Circuit Logic)
Real decisions often depend on multiple facts. For example: “Only allow access if the user is logged in and is an admin.” That’s not one comparison—it’s two comparisons combined.
Combining conditions with AND and OR
When you use && and ||, you are building compound boolean expressions.
- Use
&&when all requirements must be true. - Use
||when at least one option is acceptable.
Example (range check):
int x = 15;
if (x >= 0 && x <= 100) {
System.out.println("In range");
}
This reads as: x must be at least 0 AND x must be at most 100.
Example (outside a range):
if (x < 0 || x > 100) {
System.out.println("Out of range");
}
Short-circuit evaluation (why order matters)
Java evaluates && and || left to right, and it may stop early:
- For
p && q: ifpis false, Java does not evaluateq. - For
p || q: ifpis true, Java does not evaluateq.
This is called short-circuit evaluation, and it matters for both performance and correctness.
Correctness example (avoiding a crash):
String s = null;
if (s != null && s.equals("hi")) {
System.out.println("Greeting");
}
This is safe because if s != null is false, Java never evaluates s.equals("hi").
If you reversed the order:
if (s.equals("hi") && s != null) { // unsafe!
System.out.println("Greeting");
}
…it would crash immediately when s is null, because the first part tries to call a method.
So when one condition protects another (like a null check, or checking a denominator isn’t zero), put the protective condition first.
De Morgan’s laws (negating compound conditions)
A common task is to rewrite logic using negation. De Morgan’s laws tell you how to distribute a NOT across AND/OR:
!(p && q)is equivalent to(!p || !q)!(p || q)is equivalent to(!p && !q)
This comes up when you want to express “not (both)” or “not (either)” in a simpler or more direct way.
Example: “not in range 0..100”
// Negating the in-range condition
if (!(x >= 0 && x <= 100)) {
System.out.println("Out of range");
}
// Equivalent using De Morgan
if (x < 0 || x > 100) {
System.out.println("Out of range");
}
The second version is usually clearer.
Common logical pitfalls
Using AND when you need OR (or vice versa).
- To check if
xis outside[0, 100], you needx < 0 || x > 100. Using&&would be impossible becausexcannot be less than 0 and greater than 100 at the same time.
- To check if
Writing impossible conditions by mistake.
- Example:
x > 10 && x < 5can never be true.
- Example:
Forgetting parentheses when mixing
&&and||.- Because
&&has higher precedence than||,a || b && cmeansa || (b && c). If you intended(a || b) && c, you must use parentheses.
- Because
Exam Focus
- Typical question patterns:
- Rewrite a condition using De Morgan’s laws.
- Predict output when
&&/||short-circuits (especially with method calls). - Identify which condition correctly matches a scenario (range checks, eligibility rules).
- Common mistakes:
- Reversing De Morgan’s laws incorrectly (negating without swapping AND/OR).
- Not understanding short-circuiting and assuming both sides always run.
- Missing parentheses when mixing
&&and||, changing the meaning.
while Loops: Condition-Controlled Iteration
An iteration repeats a block of code. A while loop is ideal when you don’t know in advance how many times you need to repeat something—only that you should keep repeating while a condition stays true.
How a while loop works
The structure:
while (condition) {
// loop body
}
Step-by-step execution:
- Evaluate the condition.
- If it’s true, run the body.
- Go back to step 1.
- If it’s false, exit the loop and continue after it.
Because the condition is checked before the body runs, a while loop might run zero times.
Why while loops matter
While loops power many essential patterns:
- Repeating until the user enters a valid value (input validation)
- Repeating until a random event occurs
- Repeating until some state changes (like a game ending)
Even when you later learn arrays and ArrayLists, you still use while loops to traverse until a condition is met.
The loop invariant idea (staying oriented)
When you trace or debug loops, it helps to ask: what is always true each time the condition is checked? This idea is sometimes called an invariant. You don’t need formal proof for AP, but thinking this way keeps you from getting lost.
Example: in a loop that counts from 1 up to 5, an invariant might be: “count is the next number to print.”
Example: counting with a while loop
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
What would go wrong if you forgot count++? The condition count <= 5 would stay true forever, creating an infinite loop.
Sentinel-controlled loops (stop when you see a special value)
A sentinel value is a special value that signals “stop.” For example, -1 might mean “no more input.”
Even without user input on the AP exam, sentinel patterns show up conceptually.
int x = 3;
int sum = 0;
while (x != -1) {
sum += x;
// In real programs, you'd read a new x from input here.
// For AP-style reasoning, assume x changes somehow.
x = -1;
}
System.out.println(sum);
The essential structure is: update something in the loop, then update the variable that affects the condition.
Common while-loop mistakes
- Not updating the control variable (causes infinite loop).
- Updating the control variable in the wrong direction (for example, decrementing when you meant to increment).
- Off-by-one errors: using
<when you meant<=, or starting at the wrong initial value.
Exam Focus
- Typical question patterns:
- Trace a while loop and determine final variable values or printed output.
- Identify why a loop is infinite or why it never executes.
- Determine how many times a loop runs given initial values and an update.
- Common mistakes:
- Forgetting that the while condition is checked before the first iteration (loop may run zero times).
- Miscounting iterations due to off-by-one boundaries.
- Not noticing that the control variable is changed inside an
ifand not always updated.
for Loops: Count-Controlled Iteration
A for loop is best when you know (or can express) how many times you want to repeat something. It packages the setup, condition, and update in one place, making counting loops easier to read and less error-prone.
Anatomy of a for loop
for (initialization; condition; update) {
// body
}
How it works:
- Run the initialization once.
- Check the condition.
- If true, execute the body.
- Run the update.
- Repeat from step 2.
This is the same basic cycle as a while loop, but with a clearer “counting” structure.
Example: repeating an action a fixed number of times
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
}
This prints Hello five times because i takes values 0, 1, 2, 3, 4.
Choosing good bounds (avoiding off-by-one)
Off-by-one errors happen when you’re off by one in where you start or stop. A useful mindset is:
- If you want exactly
niterations starting from 0, usei < n. - If you want to include the endpoint, use
<=carefully.
Example: print numbers 1 through 5 (inclusive):
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Example: print numbers 1 through 5 (exclusive style):
for (int i = 1; i < 6; i++) {
System.out.println(i);
}
Both work, but you should be consistent and deliberate.
Scope of the loop variable
In for (int i = 0; ... ), the variable i is in scope only inside the loop (including the header). After the loop ends, i no longer exists.
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
// i cannot be used here
This matters in AP questions where a variable name might be reused later.
Converting between for and while
AP questions sometimes ask you to reason about equivalence. A for loop can be rewritten as a while loop by separating the three parts.
For loop:
for (int i = 0; i < 4; i++) {
System.out.println(i);
}
Equivalent while loop:
int i = 0;
while (i < 4) {
System.out.println(i);
i++;
}
Understanding this equivalence helps you trace loops and also helps you fix broken code.
Exam Focus
- Typical question patterns:
- Determine how many times a
forloop executes. - Convert a
forloop to an equivalentwhileloop (or identify whether two loops are equivalent). - Trace values of the loop variable at key points.
- Determine how many times a
- Common mistakes:
- Assuming
i <= nrunsntimes when it actually runsn + 1times if starting at 0. - Modifying the loop variable in the body in a way that breaks counting logic.
- Using the loop variable outside its scope.
- Assuming
Nested Iteration and Pattern-Based Thinking
A nested loop is a loop inside another loop. This is how you repeat a repeated process—for example, “for each day, for each hour, record a measurement.” On AP CSA, nested loops often appear in output-tracing questions because they test whether you understand the order of execution.
How nested loops execute
The most important mental model:
- The outer loop advances slowly.
- For each outer-loop iteration, the inner loop runs from start to finish.
So if the outer loop runs 3 times and the inner loop runs 4 times each time, the inner body runs 12 times total.
Example: coordinate pairs
for (int x = 1; x <= 3; x++) {
for (int y = 1; y <= 2; y++) {
System.out.println(x + "," + y);
}
}
Execution idea:
- When
x = 1, the inner loop prints1,1and1,2. - Then
x = 2, inner loop prints2,1and2,2. - Then
x = 3, inner loop prints3,1and3,2.
Example: building a simple text pattern
Nested loops are also used for patterns, like printing a rectangle of characters.
int rows = 3;
int cols = 5;
for (int r = 0; r < rows; r++) {
String line = "";
for (int c = 0; c < cols; c++) {
line += "*";
}
System.out.println(line);
}
This prints 3 lines of 5 stars.
Important note: Building strings with repeated + in a loop is not efficient in professional Java (you’d use StringBuilder), but AP CSA focuses on correctness and reasoning, and small examples like this are acceptable.
Counting iterations in nested loops
You should be comfortable computing how many times a statement runs.
For example:
for (int i = 0; i < 4; i++) {
for (int j = 2; j <= 6; j += 2) {
System.out.println(i + j);
}
}
- Outer loop:
i = 0,1,2,3→ 4 times. - Inner loop:
j = 2,4,6→ 3 times. - Total prints: 4 × 3 = 12.
The exact values printed require tracing, but the count often can be found by reasoning.
Common nested-loop mistakes
- Resetting variables incorrectly: sometimes you want to reset something at the start of each outer iteration; other times you don’t. Misplacing initialization is a frequent bug.
- Confusing which variable changes where: outer variable changes only after the entire inner loop finishes.
- Off-by-one errors become harder to notice when there are two sets of bounds.
Exam Focus
- Typical question patterns:
- Trace output of nested loops (often with
System.out.printandSystem.out.println). - Count how many times a line executes.
- Identify the order of pairs or pattern output.
- Trace output of nested loops (often with
- Common mistakes:
- Assuming the inner loop continues where it left off (it restarts each outer iteration).
- Miscounting because you forget the inner loop’s increment step (like
j += 2). - Not noticing whether the loop uses
<or<=.
Combining Selection and Iteration to Solve Problems
Most real tasks require both decisions and repetition. Selection decides whether to do something; iteration decides how many times to keep doing it. On AP CSA, many free-response style problems (and many multiple-choice questions) involve reading code where an if is inside a loop or a loop is controlled by a boolean condition built from multiple parts.
if inside a loop: filtering and conditional updates
A classic use is to update something only when a condition is met.
Example: sum only even numbers from 1 to 10.
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum); // 30
Why this structure matters:
- The loop guarantees you check each number.
- The
ifchooses whether to include it.
Common mistake: writing sum += i; outside the if, which would sum all numbers instead.
Loop controlled by a compound condition
Sometimes you keep looping while two conditions hold.
Example idea: keep trying while you have attempts left and you haven’t succeeded.
int attemptsLeft = 3;
boolean success = false;
while (attemptsLeft > 0 && !success) {
// try something
attemptsLeft--;
// pretend we succeed on the last attempt
if (attemptsLeft == 0) {
success = true;
}
}
System.out.println(success);
This example shows how state changes inside the loop can eventually make the condition false.
Input validation pattern (conceptual)
Even though AP multiple-choice questions don’t rely on real user input, the logic pattern of validation is important: keep asking (or keep checking) until the value is valid.
int age = -2;
while (age < 0) {
// in a real program, read age again
age = 10; // assume it changes
}
System.out.println("Valid age: " + age);
The key idea is that the loop represents “repeat until the condition is no longer true.”
Using break (Java feature, but handle with care)
Java supports break to exit a loop early. However, AP CSA typically emphasizes understanding loop conditions and standard traversal rather than relying heavily on break.
You might still see it in code snippets. When you do, interpret it literally: break immediately ends the nearest loop.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
// prints 1 then 2
If you’re writing your own solutions, prefer conditions that naturally stop the loop unless break clearly improves clarity.
Worked tracing example: selection inside nested loops
int count = 0;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == j) {
count++;
}
}
}
System.out.println(count);
Reasoning:
- The inner loop checks all pairs
(i, j)from 1..3. countincreases wheni == j.- Matching pairs are (1,1), (2,2), (3,3) → 3 total.
So it prints 3.
Exam Focus
- Typical question patterns:
- Trace code with
ifstatements inside loops and compute final values. - Determine how many times a conditional branch runs within nested loops.
- Identify how short-circuit logic affects loop conditions and safety (like null checks).
- Trace code with
- Common mistakes:
- Updating a variable in the wrong place (inside vs outside an
if). - Assuming a loop ends as soon as an
ifcondition is met (unless there is abreak). - Misreading
&&/||in loop conditions and not noticing short-circuit protection.
- Updating a variable in the wrong place (inside vs outside an
Tracing, Debugging, and Reasoning About Loop Correctness
AP CSA heavily tests your ability to read code: predict output, determine final variable values, and spot logic errors. Getting good at tracing isn’t just about patience—it’s about using the right structure.
A systematic tracing approach
When tracing selection and iteration, you should:
- Write down initial values of relevant variables.
- For loops: note initialization, stopping condition, and update.
- For while loops: check the condition before each iteration.
- For each iteration, record:
- the condition result
- changes to variables
- any output
This prevents you from skipping an update or accidentally applying the update twice.
Off-by-one errors: why they happen
An off-by-one error happens when your loop runs one time too many or one time too few.
Common causes:
- Using
<instead of<=(or the other way around) - Starting at 0 when you intended to start at 1
- Updating at the wrong time (pre-increment vs post-increment isn’t usually the main issue; boundary logic is)
Example: How many times does this run?
int count = 0;
for (int i = 0; i <= 5; i++) {
count++;
}
System.out.println(count);
Here i takes values 0,1,2,3,4,5 which is 6 values, so count becomes 6. Many students “feel” like 5 should mean 5 times, but <= 5 starting at 0 means 6 iterations.
Infinite loops: recognizing the cause
An infinite loop occurs when the loop condition never becomes false.
Typical causes:
- The control variable is never updated.
- The control variable changes in the wrong direction.
- The condition is written incorrectly.
Example:
int x = 1;
while (x > 0) {
System.out.println(x);
x++; // x will stay > 0 forever (until overflow, which AP typically ignores)
}
In AP reasoning, you usually treat this as infinite because x keeps increasing and the condition stays true.
Loops that never execute
The opposite problem is a loop whose condition is false at the start.
int x = 10;
while (x < 5) {
System.out.println("Hi");
}
// prints nothing
This isn’t “broken” if the logic is correct, but on the exam you must notice it.
Variable updates inside conditionals
A subtle bug pattern: updating the loop variable only in some cases.
int x = 0;
while (x < 5) {
if (x == 2) {
System.out.println("Two");
} else {
x++; // x does not increment when x == 2
}
}
When x reaches 2, the if branch runs, prints “Two,” but does not increment x. The loop becomes infinite at x == 2.
Fix: ensure the control variable updates on every path (or restructure the code).
Printing vs not printing: understanding print and println
Tracing output often depends on whether newlines occur.
System.out.print(...)prints without a newline.System.out.println(...)prints and then ends the line.
Example:
for (int i = 1; i <= 3; i++) {
System.out.print(i);
}
System.out.println("!");
Output is 123! on one line because the loop used print.
Building correct mental models with small tests
A strong strategy (even just on paper) is to test with a small value first. If a loop uses i < n, imagine n = 0, n = 1, n = 2 to see whether it behaves correctly at boundaries.
Exam Focus
- Typical question patterns:
- Trace a multi-branch loop and determine final variable values.
- Identify whether a loop is infinite, runs zero times, or runs a specific number of times.
- Determine exact printed output including spacing and newlines.
- Common mistakes:
- Losing track of when the update happens in a
forloop (after the body). - Missing a path where the loop control variable is not updated.
- Ignoring whether output uses
printorprintln, changing the displayed result.
- Losing track of when the update happens in a