TOPIC 2.3 · STUDY

if Statements

An if statement runs its body only when the condition is true. An else body runs only when that condition is false. When else is present, exactly one of the two branches runs. Without braces, the body is only the single next statement.

2.3.A

if Statements

An if statement chooses whether to run a body of code. The parentheses hold a boolean condition. When the condition is true, the if body runs. When the condition is false, that body is skipped.

A one-way if has no else. After the if finishes, the next statement after the if always runs, whether or not the body ran. Adding else makes two-way selection: the else body runs only when the condition is false.

int score = 82;
if (score >= 70)
    System.out.print("pass");
else
    System.out.print("retry");

score >= 70 is true, so the if body prints pass and the else body does not run. If score were 60 instead, the if body would be skipped and the else body would print retry. In either case, exactly one of those two print statements runs.

A condition box at the top sends one arrow left to the if body when true and one arrow right to the else body when false.

True takes the if body. False takes the else body. With else present, only one path runs.

Without braces, the body of an if or else is only the single next statement. Any later statement at the same indentation is not part of that body. Use braces when more than one statement should run together as the body.

int seats = 3;
if (seats > 5)
    seats = seats - 1;
seats = seats + 2;
System.out.print(seats);

Only seats = seats - 1; belongs to the if. seats > 5 is false, so that line is skipped. seats = seats + 2; always runs, so the printed value is 5.

Key points

  • if (condition) runs its body only when the condition is true.
  • else runs its body only when the condition is false.
  • When else is present, exactly one of the two branches runs.
  • Without braces, the body is only the single next statement.
  • Code after the if or if-else still runs afterward.

When else is present, exactly one branch runs. The if body and the else body never both run for the same condition check.

Practice this topic