AP Computer Science A · Study guide

One-Way and Two-Way Selection

AP® Computer Science A · Selection and Iteration

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.

Big Picture

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.

FormSyntaxWhat runs
One-way selectionif (condition) { body }The body, only when the condition is true
Two-way selectionif (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.

Figure 1. In a one-way selection, the body is executed only when the Boolean expression is true. Either way, execution continues with the next statement.
Worked Example 1 One-way selection

A Discount That Applies Only Sometimes

A shop takes 5 off orders of 50 or more. Predict the output for each total.

total is 62
int total = 62;
if (total >= 50)
{
    total = total - 5;
}
System.out.println("Pay " + total);
Output
Pay 57
total is 38
int total = 38;
if (total >= 50)
{
    total = total - 5;
}
System.out.println("Pay " + total);
Output
Pay 38
  1. 162. The condition is true, so the body runs: 62 − 5 = 57.
  2. 238. The condition is false, so the body is skipped and the total is unchanged.
  3. 3Both runs reach the println, which is outside the if.
Result: The outputs are Pay 57 and Pay 38. A one-way selection runs its body only when the condition is true and otherwise does nothing extra.
totaltotal >= 50Body runs?Printed
62trueyes: 62 − 5Pay 57
50trueyes: 50 − 5Pay 45
49falsenoPay 49
38falsenoPay 38
Common Mistake 1 · Expecting the Body to Run More Than Once

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.

Figure 2. In a two-way selection, the body of the if runs when the Boolean expression is true and the body of the else runs when it is false: exactly one of them.
Figure 3. An if statement has a Boolean expression in parentheses followed by a body; else adds a second body with no condition of its own.
Worked Example 2 Two-way selection

Even or Odd

Predict the output.

Code
int n = 7;
if (n % 2 == 0)
{
    System.out.println(n + " is even");
}
else
{
    System.out.println(n + " is odd");
}
System.out.println("done");
Output
7 is odd
done
  1. 1The condition. 7 % 2 is 1, and 1 == 0 is false.
  2. 2The else body runs: "7 is odd". The if body is skipped.
  3. 3Then execution continues after the whole statement: "done".
Result: The output is 7 is odd, then done. In a two-way selection exactly one body runs: the if body for true, the else body for false.
Worked Example 3 Two ways to write it

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.

One-way with a default
double total = 40;
double shipping = 4.99;
if (total >= 35)
{
    shipping = 0;
}
System.out.println(shipping);
Output
0.0
Two-way
double total = 40;
double shipping;
if (total >= 35)
{
    shipping = 0;
}
else
{
    shipping = 4.99;
}
System.out.println(shipping);
Output
0.0
  1. 1One-way version. Start with the usual value, then change it only in the special case.
  2. 2Two-way version. Assign the value in both branches; exactly one runs, so shipping is always given a value.
  3. 3For an order of 40, the condition is true in both versions, and shipping is 0.0.
Result: Both print 0.0. A one-way selection with a default and a two-way selection that assigns in both branches are equivalent ways to choose between two values.
Common Mistake 2 · Giving else a Condition

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 ==.

Worked Example 4 Conditions from methods

Using a boolean Result as the Condition

Any expression of type boolean can be the condition, including a method call. Predict the output.

Code
String answer = "Yes";
if (answer.equals("yes"))
{
    System.out.println("Confirmed");
}
else
{
    System.out.println("Not confirmed: " + answer);
}
Output
Not confirmed: Yes
  1. 1The condition is the boolean returned by equals.
  2. 2"Yes" vs "yes". equals is case-sensitive, so it returns false.
  3. 3The else body runs.
Result: The output is Not confirmed: Yes. A condition can be any Boolean expression: a comparison, a 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.

Figure 4. Java ignores indentation. Without braces, only one statement belongs to the if; the next line runs every time.
ErrorExampleEffect
Missing braces around two statementsif (c) s1; s2;Only s1 is controlled; s2 always runs
Semicolon after the conditionif (c); { s1; }The if does nothing; s1 always runs
Condition on elseelse (x < 5)Does not compile: else has no condition
Non-boolean conditionif (x = 5)Does not compile
Worked Example 5 Missing braces

When Indentation Misleads

The programmer meant both lines to belong to the if. Predict the actual output.

Code
int temp = 30;
if (temp < 10)
    System.out.println("cold");
    System.out.println("wear a coat");
System.out.println("bye");
Output
wear a coat
bye
  1. 1No braces. The body of the if is only the first statement after the condition: the "cold" line.
  2. 2The condition is false (30 < 10), so "cold" is skipped.
  3. 3"wear a coat" is outside the if, despite its indentation, so it always runs (Figure 4).
Result: The output is wear a coat, then bye. Java ignores indentation; always surround a body with braces so the code does what it looks like.
Worked Example 6 Stray semicolon

A Semicolon After the Condition

Predict the output.

Code
int temp = 30;
if (temp < 10);
{
    System.out.println("cold");
}
Output
cold
  1. 1The semicolon ends the if. if (temp < 10); has an empty body: when the condition is true, nothing happens.
  2. 2The block in braces is a separate statement that is not controlled by the if, so it always runs.
  3. 3Result. "cold" prints even though 30 is not less than 10.
Result: The output is cold. A semicolon directly after the condition makes the if do nothing; the following block runs every time. Never put a semicolon after if (...).
Common Mistake 3 · Trusting Indentation

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.

Worked Example 7 if-else in a method

Returning One of Two Values

Predict the output.

Code
public static int larger(int a, int b)
{
    if (a > b)
    {
        return a;
    }
    else
    {
        return b;
    }
}
Output
9
9
5
  1. 1larger(4, 9). 4 > 9 is false: the else branch returns 9.
  2. 2larger(9, 4). true: the if branch returns 9.
  3. 3larger(5, 5). 5 > 5 is false: the else branch returns b, which is 5. Equal values are handled correctly either way.
Result: The output is 9, 9, 5. A two-way selection guarantees that one of the two return statements runs, so the method always returns a value.
Common Mistake 4 · Forgetting the Equal Case

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.

Core Synthesis

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.