Unit 2 · 15 min
2.3 if Statements
An if statement lets the value of a Boolean expression decide which code runs.
Summary, objectives and course and exam description (CED) codes
Selection statements change the sequential execution of statements. An if statement affects the flow of control by running different segments of code based on the value of a Boolean expression. A one-way selection (if) runs its body only when the expression is true; a two-way selection (if-else) runs the if body when it is true and the else body when it is false.
By the end of this session you can
- 2.3.A Develop code to represent branching logical processes by using selection statements and determine the result of these processes.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Selection changes the flow of control
Normally Java runs statements in sequence, top to bottom. Selection statements change that sequential execution 2.3.A.1. An if statement is a type of selection statement: it affects the flow of control by running different segments of code depending on the value of a Boolean expression 2.3.A.2.
boolean isRaining = true;
if (isRaining) {
// body: runs only when the Boolean expression is true
}
// the program continues here in every case
The condition must be a Boolean expression inside parentheses. It can be a relational expression (score >= 70) or a boolean variable (isMember).
2. One-way selection: if
Use a one-way selection (if statement) when some code should run in one situation and be skipped otherwise. If the Boolean expression is true, the body runs; if it is false, the body is skipped 2.3.A.3.
int battery = 15;
System.out.println("Checking battery...");
if (battery < 20) {
System.out.println("Low battery: plug in your phone");
}
System.out.println("Battery: " + battery + "%");
Output:
Checking battery...
Low battery: plug in your phone
Battery: 15%
Trace with two different starting values:
| battery | battery < 20 | Lines printed |
|---|---|---|
| 15 | true | Checking, Low battery, Battery: 15% |
| 80 | false | Checking, Battery: 80% |
The last println is after the if, so it runs in both cases.
3. Two-way selection: if-else
Use a two-way selection (if-else statement) when the program has two different segments of code to choose from: one for a true Boolean expression and one for a false one. The if body runs when the expression is true, and the else body runs when it is false 2.3.A.4. Exactly one of the two bodies runs.
int score = 64;
if (score >= 70) {
System.out.println("Passed");
} else {
System.out.println("Try again");
}
System.out.println("Done");
Output:
Try again
Done
Inside a method, each branch can return a value. Every path through the method must reach a return.
public static String parity(int n) {
if (n % 2 == 0) {
return "even";
} else {
return "odd";
}
}
System.out.println(parity(14));
System.out.println(parity(-3));
Output:
even
odd
4. Two ifs are not an if-else
Two separate if statements are checked one after the other, so both bodies can run. Compare this with the if-else in Section 3.
int temp = 30;
if (temp > 25) {
System.out.println("Hot");
}
if (temp > 10) {
System.out.println("Warm");
}
Output:
Hot
Warm
Separate ifs can also change a value that the next if then checks:
int coins = 8;
if (coins < 10) {
coins += 5;
}
if (coins >= 10) {
System.out.println("Bonus unlocked");
}
System.out.println(coins);
Output:
Bonus unlocked
13
5. Braces and the stray semicolon
Java ignores indentation. Without braces, an if controls only the very next statement.
int speed = 40;
if (speed > 50)
System.out.println("Slow down");
System.out.println("Speeding ticket");
Output:
Speeding ticket
The second println looks like it is inside the if, but it is not, so it runs even though speed > 50 is false.
A semicolon right after the condition is worse: it gives the if an empty body, and the block below always runs.
int speed = 40;
if (speed > 50); {
System.out.println("Slow down");
}
Output:
Slow down
Watch out: an else with no matching if (for example, after a stray semicolon) does not compile:
int speed = 40;
if (speed > 50); {
System.out.println("Slow down");
} else {
System.out.println("OK");
}
error: 'else' without 'if'
Rule for the exam and for your own code: put braces around every if and else body, and never put a semicolon after if (...).
Lock it in: memory hooks
- One-way selectionif is a door: true opens it, false walks past it.
- Two-way selectionif-else is a fork: you always take exactly one road.
- Stray semicolonA semicolon after if (...) is an empty body: the door opens onto nothing.
Common misconceptions
"Indentation decides which statements belong to the if."
Not quite. Java ignores indentation. Without braces, only the first statement after the if is controlled by it. Use braces every time.
"Two separate if statements work the same as an if-else."
Not quite. Separate if statements are each checked, so both bodies can run. In an if-else exactly one of the two bodies runs.
"The else needs its own condition."
Not quite. else has no condition. It runs exactly when the if condition is false.
Exam traps
- if (x > 5); with a semicolon: the block below runs every time, because the if controls an empty statement.
- No braces: only the first statement is inside the if, no matter how the code is indented.
- Two ifs in a row can both run; an if-else never runs both bodies.
- Statements after the whole if-else always run, whatever the condition was.
2PracticeRecall it, then check yourself
In 30 seconds
- Without selection, statements run in order, top to bottom. Selection statements change that sequential execution.
- An if statement runs a segment of code based on the value of a Boolean expression.
- One-way selection (if): the body runs only when the Boolean expression is true.
- Two-way selection (if-else): the if body runs when true, the else body when false. Exactly one runs.
- Always use braces. A semicolon right after the condition ends the if statement.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: 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
- Kinds of selection in this topic two kinds CED 2.3.A.3, 2.3.A.4
- one-way selection (if statement)body runs only when true
- two-way selection (if-else statement)if body when true, else body when false
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.
-
Selectiontap to flip
An algorithm building block in which a true or false decision chooses how the execution of the algorithm proceeds.
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 -
Relational operatorstap to flip
The operators ==, !=, <, >, <= and >=, which compare two values and evaluate to a Boolean value.
Example and CED codes
Questions students ask
What is the difference between an if statement and an if-else statement?
An if statement (one-way selection) runs its body only when the condition is true and does nothing otherwise. An if-else statement (two-way selection) always runs exactly one of two bodies.
Do I need braces in a Java if statement?
Java allows an if without braces, but then only the next single statement is controlled. Using braces always avoids hard-to-see logic errors.
Why does my if body run even when the condition is false?
Check for a semicolon right after the closing parenthesis, such as if (x > 5);. That semicolon is an empty body, so the block that follows is not part of the if.
Can an if statement return a value from a method?
Yes. A method can use an if-else with a return statement in each branch. Every path through the method must return a value.