One-Way and Two-Way Selection
The if statement and the if-else statement: how a Boolean expression decides which code runs, how to trace selection with different values, and the brace and semicolon mistakes that make code do something other than what it appears to do.
Selection statements change the sequential execution of statements. An if statement is a type of selection statement that affects the flow of control by executing 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) has two bodies: the if body runs when the expression is true, and the else body runs when it is false.
1Changing the Flow of Control
Without selection, a program runs every statement once, from top to bottom. Selection statements change the sequential execution of statements: depending on the value of a Boolean expression, some statements run and others are skipped. This is how a program reacts to its data, charging shipping only for small orders, printing a warning only when a value is out of range, or choosing a message based on a score.
Every selection has the same ingredients: a condition, which is a Boolean expression written in parentheses, and one or more bodies, blocks of statements in braces. Java evaluates the condition once, when the if is reached, and uses the result to decide which body, if any, to run. After that, execution continues with the statement following the whole if structure.
Because the condition is evaluated only once, at the moment the if is reached, changes made inside a body do not cause a second check. If the body of an if changes a variable that appears in the condition, the new value matters only to statements that come later; the decision has already been made.
| Form | Syntax | What runs |
|---|---|---|
| One-way selection | if (condition) { body } | The body, only when the condition is true |
| Two-way selection | if (condition) { A } else { B } | A when true, B when false: exactly one |
2One-Way Selection: if
A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. The body is executed only when the Boolean expression is true; when it is false, the body is skipped entirely and execution continues after it.
One-way selection suits "extra" actions that happen only sometimes: applying a discount, adding a bonus, printing a warning. The statements before and after the if run in every case. When tracing, evaluate the condition with the current values, then either run the body or jump past it; testing values on both sides of the boundary, and the boundary itself, confirms the condition is right.
true. Either way, execution continues with the next statement.A Discount That Applies Only Sometimes
A shop takes 5 off orders of 50 or more. Predict the output for each total.
int total = 62;
if (total >= 50)
{
total = total - 5;
}
System.out.println("Pay " + total);
Pay 57
int total = 38;
if (total >= 50)
{
total = total - 5;
}
System.out.println("Pay " + total);
Pay 38
- 162. The condition is
true, so the body runs: 62 − 5 = 57. - 238. The condition is
false, so the body is skipped and the total is unchanged. - 3Both runs reach the
println, which is outside theif.
| total | total >= 50 | Body runs? | Printed |
|---|---|---|---|
| 62 | true | yes: 62 − 5 | Pay 57 |
| 50 | true | yes: 50 − 5 | Pay 45 |
| 49 | false | no | Pay 49 |
| 38 | false | no | Pay 38 |
An if statement checks its condition once and runs its body at most once. It is not a loop. If a task must repeat while a condition holds, that calls for repetition, written with while or for.
3Two-Way Selection: if-else
A two-way selection (if-else statement) is used when there are two segments of code: one to be executed when the Boolean expression is true and another for when it is false. The body of the if is executed when the expression is true, and the body of the else is executed when the expression is false. Exactly one of the two bodies runs every time.
The else keyword has no condition of its own; it simply means "otherwise." Two-way selection suits either-or situations: even or odd, pass or fail, member price or regular price. Because one branch always runs, an if-else is a reliable way to give a variable a value in every case.
Many either-or decisions can be written in two equivalent ways: as an if-else that assigns a value in each branch, or as a default value followed by a one-way if that changes it in the special case. Choose whichever states the logic most clearly; the default-then-adjust style often reads well when one outcome is the usual one and the other is an exception.
if runs when the Boolean expression is true and the body of the else runs when it is false: exactly one of them.if statement has a Boolean expression in parentheses followed by a body; else adds a second body with no condition of its own.Even or Odd
Predict the output.
int n = 7;
if (n % 2 == 0)
{
System.out.println(n + " is even");
}
else
{
System.out.println(n + " is odd");
}
System.out.println("done");
7 is odd
done
- 1The condition. 7 % 2 is 1, and 1 == 0 is
false. - 2The else body runs: "7 is odd". The if body is skipped.
- 3Then execution continues after the whole statement: "done".
A Default Value Versus if-else
Shipping costs 4.99 unless the order is at least 35, when it is free. Both versions give the same result. Predict the output for an order of 40.
double total = 40;
double shipping = 4.99;
if (total >= 35)
{
shipping = 0;
}
System.out.println(shipping);
0.0
double total = 40;
double shipping;
if (total >= 35)
{
shipping = 0;
}
else
{
shipping = 4.99;
}
System.out.println(shipping);
0.0
- 1One-way version. Start with the usual value, then change it only in the special case.
- 2Two-way version. Assign the value in both branches; exactly one runs, so
shippingis always given a value. - 3For an order of 40, the condition is
truein both versions, and shipping is 0.0.
else (n % 2 != 0) does not compile. The else branch runs exactly when the if condition is false, so it needs no condition. Write just else followed by its body.
4Writing Conditions
The condition can be any expression of type boolean: a relational comparison such as total >= 50, a boolean variable such as isMember, or a call to a method that returns a boolean, such as answer.equals("yes"). Whatever form it takes, it must evaluate to true or false.
Writing a correct condition is mostly about choosing the right comparison. Decide which values should make the body run, identify the boundary, and choose < or <= accordingly. For strings, use equals, remembering that it is case-sensitive; for computed double values, avoid ==.
Using a boolean Result as the Condition
Any expression of type boolean can be the condition, including a method call. Predict the output.
String answer = "Yes";
if (answer.equals("yes"))
{
System.out.println("Confirmed");
}
else
{
System.out.println("Not confirmed: " + answer);
}
Not confirmed: Yes
- 1The condition is the
booleanreturned byequals. - 2"Yes" vs "yes".
equalsis case-sensitive, so it returnsfalse. - 3The else body runs.
boolean variable, or a method that returns boolean.5Braces, Blocks, and Semicolons
The body of an if or else is normally a block in braces, which may contain any number of statements. Java does allow a body without braces, but then the body is only the single statement immediately after the condition. Java ignores indentation, so a second indented line that looks like part of the body actually runs every time.
A semicolon directly after the condition, as in if (temp < 10);, is an even sneakier error: it gives the if an empty body, and the block that follows becomes an ordinary statement that always runs. Both mistakes compile without complaint, which is why the safest habit is simple: always write braces, and never put a semicolon after the parentheses of an if.
if; the next line runs every time.| Error | Example | Effect |
|---|---|---|
| Missing braces around two statements | if (c) s1; s2; | Only s1 is controlled; s2 always runs |
| Semicolon after the condition | if (c); { s1; } | The if does nothing; s1 always runs |
| Condition on else | else (x < 5) | Does not compile: else has no condition |
| Non-boolean condition | if (x = 5) | Does not compile |
When Indentation Misleads
The programmer meant both lines to belong to the if. Predict the actual output.
int temp = 30;
if (temp < 10)
System.out.println("cold");
System.out.println("wear a coat");
System.out.println("bye");
wear a coat
bye
- 1No braces. The body of the
ifis only the first statement after the condition: the "cold" line. - 2The condition is false (30 < 10), so "cold" is skipped.
- 3"wear a coat" is outside the
if, despite its indentation, so it always runs (Figure 4).
A Semicolon After the Condition
Predict the output.
int temp = 30;
if (temp < 10);
{
System.out.println("cold");
}
cold
- 1The semicolon ends the
if.if (temp < 10);has an empty body: when the condition is true, nothing happens. - 2The block in braces is a separate statement that is not controlled by the
if, so it always runs. - 3Result. "cold" prints even though 30 is not less than 10.
if do nothing; the following block runs every time. Never put a semicolon after if (...).Indentation is for human readers; the compiler uses braces. When code is indented as if two statements belong to an if but there are no braces, only the first is controlled. When tracing someone else's code, look for the braces, not the indentation.
6Selection Inside Methods
Selection often decides what a method returns. In larger(a, b), an if-else returns a in one branch and b in the other; because exactly one branch runs, the method always returns a value. A return statement ends the method immediately, so no statement after it in the same method runs.
When writing methods with selection, check every path through the code. Each possible combination of conditions should lead to the intended result, including equal values and boundary cases. A method that returns a value must return one on every path; the compiler reports an error if some path could reach the end without a return.
Returning One of Two Values
Predict the output.
public static int larger(int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
9
9
5
- 1
larger(4, 9). 4 > 9 isfalse: the else branch returns 9. - 2
larger(9, 4).true: the if branch returns 9. - 3
larger(5, 5). 5 > 5 isfalse: the else branch returnsb, which is 5. Equal values are handled correctly either way.
return statements runs, so the method always returns a value.In a method that compares a and b, consider what happens when they are equal. if (a > b) ... else ... sends equal values to the else branch. Make sure that branch gives the correct answer for that case too.
Four Habits for if and if-else
1. Evaluate, Then Branch
Compute the condition with current values, then pick the body.
2. Exactly One for if-else
The if body or the else body runs, never both.
3. Always Use Braces
Indentation never defines a body.
4. No Semicolon After if (...)
It empties the body and the block always runs.
Selection statements change the sequential execution of statements. An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression. A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition, and its body is executed only when the Boolean expression is true. A two-way selection (if-else statement) is used when there are two segments of code: the body of the if is executed when the Boolean expression is true, and the body of the else is executed when it is false.