Unit 2 · 16 min
2.4 Nested if Statements
Nesting and chaining let a program make a decision that depends on earlier decisions.
Summary, objectives and course and exam description (CED) codes
Nested if statements are if, if-else or if-else-if statements placed inside other if, if-else or if-else-if statements. The inner Boolean expression is evaluated only when the outer one is true. A multiway selection (if-else-if) runs at most one segment of code: the one for the first expression that evaluates to true, or the trailing else if none is true.
By the end of this session you can
- 2.4.A Develop code to represent nested branching logical processes and determine the result of these processes.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. An if inside an if
Nested if statements are if, if-else or if-else-if statements written inside the body of another if, if-else or if-else-if statement 2.4.A.1. Use nesting when a second decision only makes sense after the first one.
A cinema charges by age, but only members get the student price:
int age = 15;
boolean isMember = true;
if (age < 18) {
if (isMember) {
System.out.println("Ticket: 5 dollars");
} else {
System.out.println("Ticket: 8 dollars");
}
} else {
System.out.println("Ticket: 12 dollars");
}
Output:
Ticket: 5 dollars
2. The inner condition waits for the outer one
The Boolean expression of the inner if is evaluated only if the outer Boolean expression is true 2.4.A.2. Trace the cinema code with four inputs:
| age | isMember | age < 18 | isMember checked? | Output |
|---|---|---|---|---|
| 15 | true | true | yes, true | Ticket: 5 dollars |
| 15 | false | true | yes, false | Ticket: 8 dollars |
| 30 | true | false | no | Ticket: 12 dollars |
| 30 | false | false | no | Ticket: 12 dollars |
When the outer test is false, Java jumps straight to the outer else. The value of isMember does not matter.
3. Multiway selection: if-else-if
A multiway selection (if-else-if) is used when there is a series of expressions, each with its own segment of code. Java checks the expressions from top to bottom, runs no more than one segment (the one for the first expression that evaluates to true) and skips the rest. If no expression is true and there is a trailing else, the else body runs 2.4.A.3.
int score = 84;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
System.out.println("Grade: " + grade);
Output:
Grade: B
score >= 70 is also true for 84, but it is never checked, because score >= 80 was true first.
| score | First true expression | grade |
|---|---|---|
| 95 | score >= 90 | A |
| 84 | score >= 80 | B |
| 70 | score >= 70 | C |
| 42 | none, trailing else | F |
4. Order matters in a chain
Because the first true expression wins, the order of the conditions changes the result. This version checks the widest condition first:
int score = 95;
String grade;
if (score >= 70) {
grade = "C";
} else if (score >= 80) {
grade = "B";
} else if (score >= 90) {
grade = "A";
} else {
grade = "F";
}
System.out.println("Grade: " + grade);
Output:
Grade: C
A score of 95 gets a C, because score >= 70 is true first. The B and A branches can never run. Rule: with >=, put the largest boundary first; with <=, put the smallest boundary first.
Without a trailing else, a chain may run nothing at all:
int windSpeed = 12;
if (windSpeed > 60) {
System.out.println("Storm warning");
} else if (windSpeed > 30) {
System.out.println("Strong wind");
}
System.out.println("Report finished");
Output:
Report finished
5. The dangling else
When there are no braces, an else pairs with the nearest earlier if that does not already have an else, no matter how the code is indented. This is called the dangling else.
int x = 5;
int y = 1;
if (x > 3)
if (y > 3)
System.out.println("Both big");
else
System.out.println("x is small");
Output:
x is small
The else is indented under if (x > 3), but it belongs to if (y > 3). Since x > 3 is true and y > 3 is false, the inner else runs and prints a message that is wrong. With braces, the meaning matches the indentation:
int x = 5;
int y = 1;
if (x > 3) {
if (y > 3) {
System.out.println("Both big");
}
} else {
System.out.println("x is small");
}
System.out.println("End");
Output:
EndLock it in: memory hooks
- Nested ifA door behind a door: you only reach the inner door if the outer one opened.
- Multiway selectionFirst true wins, the rest are skipped.
- Dangling elseelse marries the closest single if, not the one it looks at.
Common misconceptions
"In an if-else-if chain, every condition that is true runs its code."
Not quite. Only the first true condition runs its segment. Java skips all the remaining conditions in the chain, even if they are also true.
"An else belongs to the if it is lined up with."
Not quite. Java ignores indentation. Without braces, an else pairs with the nearest earlier if that does not already have an else.
"An if-else-if chain always runs one segment."
Not quite. Only when it ends with a trailing else. Without one, it is possible that no segment runs.
Exam traps
- A wrongly ordered chain such as checking score >= 60 before score >= 90 gives every passing student the lowest grade.
- Dangling else: without braces, the else belongs to the inner if, so it runs when the outer condition is true and the inner one is false.
- In nested code, if the outer condition is false, the inner condition is never evaluated, even if it would be true.
- A chain of separate ifs is not a multiway selection: several bodies can run.
2PracticeRecall it, then check yourself
In 30 seconds
- A nested if statement is a selection statement inside the body of another selection statement.
- The inner condition is evaluated only if the outer condition is true.
- if-else-if (multiway selection) runs no more than one segment: the first true expression wins.
- If nothing is true and there is a trailing else, the else body runs. With no trailing else, nothing runs.
- Order conditions from most specific to least specific (for example, highest grade boundary first).
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: Nested if Statements
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Statements that can be nested inside each other three statements CED 2.4.A.1
- if
- if-else
- if-else-if
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Nested if statementtap to flip
An if, if-else or if-else-if statement inside the body of another one. The inner Boolean expression is evaluated only if the outer one is true.
Example and CED codes -
Multiway selectiontap to flip
An if-else-if chain that runs at most one segment of code: the one for the first expression that evaluates to true, or the trailing else if none is true.
Example and CED codes -
if statementtap to flip
A selection statement that runs its body only when its Boolean expression is true, changing the flow of control.
Example and CED codes -
if-else statementtap to flip
A two-way selection: the if body runs when the Boolean expression is true, and the else body runs when it is false. Exactly one of them runs.
Example and CED codes -
Boolean expressiontap to flip
An expression that evaluates to a Boolean value, true or false, such as a comparison with a relational operator or a combination with logical operators.
Example and CED codes
Questions students ask
What is a nested if statement in Java?
An if, if-else or if-else-if statement placed inside the body of another one. The inner condition is checked only when the outer condition is true.
How does an if-else-if chain work?
Java checks the conditions from top to bottom and runs the segment for the first one that is true, then skips the rest. If none is true, the trailing else runs, if there is one.
What is the dangling else problem?
When an else could belong to more than one if, Java pairs it with the nearest unmatched if, regardless of indentation. Braces remove the problem.
When should I use a nested if instead of &&?
Use a nested if when the outer and inner decisions each need their own else or extra code. When you only need both conditions to be true for one action, && is shorter (Topic 2.5).