From the free course AP Computer Science A on Lykke
2.4 Nested if Statements
Key concepts: Nested if statements · Logical equivalence of nested conditions and the || operator · Equality comparison using == · Conditional logic · Two-dimensional array element assignment · Identifying pairs of elements · Iteration · Counting algorithms · Sequential if statements · Combining conditions with logical operators
A nested if statement places one conditional statement inside another, allowing a program to test a second condition only after a first condition succeeds. This creates a decision structure like a security checkpoint: first verify that a person has a ticket, then—only for ticket holders—check whether the ticket is…
2.4 Nested if Statements
A nested if statement places one conditional statement inside another, allowing a program to test a second condition only after a first condition succeeds. This creates a decision structure like a security checkpoint: first verify that a person has a ticket, then—only for ticket holders—check whether the ticket is for today.
Learning Objective 2.4.A — Develop code to implement nested if statements. The central knowledge statement is Essential Knowledge 2.4.A.1: nested if statements allow one condition to control whether another condition is tested.
The control-flow shape
The inner condition is unreachable when the outer condition is false. In the example below, the program prints "large and even" only when both tests succeed.
if (number > 100) {
if (number % 2 == 0) {
System.out.println("large and even");
}
}
Trace the conditions in order:
- If
number > 100is false, skip the entire innerif. - If
number > 100is true, evaluatenumber % 2 == 0. - Print only if both conditions are true.
The two tests are logically equivalent to a single condition using || only when the desired outcomes are arranged appropriately. For example, two separate inner checks can represent “the elements are equal or their sum is $10$”:
if (samePair) {
puzzle[i][j] = 0;
}
if (sumIsTen) {
puzzle[i][j] = 0;
}
When both checks assign the same value, this can be expressed as one conditional action:
if (samePair || sumIsTen) {
puzzle[i][j] = 0;
}
The important distinction is that nested conditions and compound conditions describe different control-flow shapes, even when they produce the same result. A nested structure is useful when the second test should occur only after the first succeeds; a combined condition is useful when several alternatives lead directly to the same action.
Worked example: identifying a matching pair
Suppose puzzle is a two-dimensional integer array. An algorithm examines candidate pairs of elements. A pair qualifies if the two elements are equal, or if their values add to $10$. When it finds the first qualifying pair, it sets the current element to $0$ and immediately returns true.
public boolean clearPair(int[][] puzzle) {
for (int i = 0; i < puzzle.length; i++) {
for (int j = 0; j < puzzle[i].length; j++) {
for (int row = 0; row < puzzle.length; row++) {
for (int col = 0; col < puzzle[row].length; col++) {
if (puzzle[i][j] == puzzle[row][col]) {
puzzle[i][j] = 0;
return true;
}
if (puzzle[i][j] + puzzle[row][col] == 10) {
puzzle[i][j] = 0;
return true;
}
}
}
}
}
return false;
}
The first nested if uses == to test equality: it asks whether the two array elements contain the same integer value. The second nested if performs a mathematical computation and tests whether the sum equals $10$.
This exact loop structure includes self-pairs, such as comparing puzzle[i][j] with itself, and reversed duplicates, such as examining both (i, j) with (row, col) and later (row, col) with (i, j). That may cause an immediate match—for example, every element equals itself—so a production algorithm would usually need additional bounds or a condition excluding identical positions. The code above is valuable for tracing the stated nested-condition pattern, but its pair-selection policy must match the problem’s specification.
Because return true occurs inside the loops, the method does not examine every possible pair. It examines candidate pairs until the first match, clears an element of that pair, and stops. If no qualifying pair is found, execution reaches return false after all candidates have been considered.
One action can clear either element
If the algorithm’s requirement is merely to mark an identified pair as handled, assigning 0 to puzzle[i][j] may be sufficient. Assigning both puzzle[i][j] and puzzle[row][col] also clears the pair, but the scoring logic described for this pattern awards the assignment when either identified element is set correctly.
A common misconception is that = checks whether two values are equal. It does not: = assigns a value, while == compares two values. Thus puzzle[i][j] == puzzle[row][col] asks a question, whereas puzzle[i][j] = 0 changes stored data.
Two unrelated conditions
Nested or sequential if statements also handle unrelated conditions inside a larger algorithm. For example, a feeding simulation might separately determine whether birds visit and how much food is added, while another condition determines whether a bear empties the feeder. The conditions should not be accidentally nested if one event is not supposed to depend on the other.
The same reasoning appears in counting algorithms. To count the longest consecutive run of temperatures above a threshold, maintain a current count, reset it when the condition fails, and update the maximum when the current run becomes larger.
int current = 0;
int longest = 0;
for (int i = 0; i < temperatures.size(); i++) {
if (temperatures.get(i) > threshold) {
current++;
if (current > longest) {
longest = current;
}
} else {
current = 0;
}
}
This uses iteration, conditional logic, and a mathematical comparison together. The inner if can be replaced by a logical expression in an appropriate redesign, but the essential trace remains: identify the qualifying values, count consecutive successes, reset after a failure, and preserve the largest count.
Skill connection and retrieval check
This topic most directly exercises Computational Thinking Practice 2 — Develop Code when implementing nested conditions and two-dimensional assignments, and Computational Thinking Practice 3 — Analyze Code when tracing which conditions execute, which pair is found first, and when return stops iteration.
Retrieval check: If puzzle[i][j] is $6$ and puzzle[row][col] is $4$, which condition in the worked algorithm succeeds? If the values are $6$ and $6$, which condition succeeds first? Remember: the equality test is ==, the sum test is + ... == 10, and the first successful return true ends the search.

Source Materials
- AP Computer Science A Course and Exam Description
- AP Computer Science A Course and Exam Description Clarifications and Corrections
- AP Computer Science A Course Overview
- AP Computer Science A Course at a Glance
- AP Computer Science A Course at a Glance Poster
- Adopt AP Computer Science A
- AP Computer Science A
- AP Computer Science A