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.

2.3.A2.3.A.12.3.A.22.3.A.32.3.A.4

Reviewed against the CED on

Know this already? Jump to the checkpoint.

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

  1. Without selection, statements run in order, top to bottom. Selection statements change that sequential execution.
  2. An if statement runs a segment of code based on the value of a Boolean expression.
  3. One-way selection (if): the body runs only when the Boolean expression is true.
  4. Two-way selection (if-else): the if body runs when true, the else body when false. Exactly one runs.
  5. 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.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 2.3.A.2, 2.3.A.3
    int x = 12;
    if (x > 10)
        x -= 5;
        x *= 2;
    System.out.println(x);
    Show answer

    Answer: C. Without braces, the if controls only x -= 5;. Since 12 > 10, x becomes 7. The statement x *= 2; is not part of the if (indentation does not matter), so it always runs and x becomes 14. 7 ignores the second statement, and 24 skips the subtraction.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.3.A.1, 2.3.A.3
    int points = 3;
    if (points > 5); {
        points += 10;
    }
    System.out.println(points);
    Show answer

    Answer: A. The semicolon after the condition is an empty statement, and it is the whole body of the if. The block { points += 10; } is an ordinary block after the if, so it always runs and points becomes 13. Answering 3 assumes the block belongs to the if. The code compiles, because an empty statement is legal.

  3. 3 Consider the following code segment. What is printed as a result of executing the code segment? 2.3.A.3, 2.3.A.4
    int t = 18;
    String s = "";
    if (t > 15) {
        s += "A";
    }
    if (t > 10) {
        s += "B";
    } else {
        s += "C";
    }
    System.out.println(s);
    Show answer

    Answer: A. The two if statements are separate, so both are checked. 18 > 15 adds "A". In the if-else, 18 > 10 is true, so the if body adds "B" and the else body is skipped. "ABC" would need both bodies of the if-else to run, which never happens.

  4. 4 Which of the following best describes a two-way selection (if-else statement)? 2.3.A.4
    Show answer

    Answer: C. In an if-else, the if body runs when the Boolean expression is true and the else body runs when it is false, so exactly one of them runs. Both bodies never run, and the else body is never run before the condition is checked. The last option reverses the meaning of the two bodies.

  5. 5 Consider the following method. What value is returned by the call shipping(20)? 2.3.A.2, 2.3.A.3
    public static int shipping(int weight) {
        if (weight > 20) {
            return 15;
        }
        if (weight > 5) {
            return 8;
        }
        return 3;
    }
    Show answer

    Answer: B. 20 > 20 is false, so the first return is skipped. 20 > 5 is true, so the method returns 8 and ends. 15 would require a weight above 20 (the boundary 20 is not included by >). 26 adds the values, but a return ends the method, so only one value is returned.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Kinds of selection in this topic two kinds CED 2.3.A.3, 2.3.A.4
    1. one-way selection (if statement)body runs only when true
    2. 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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure