ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.3

if Statements

Skill 2.ASkill 3.ASkill 4.A

Big idea: An if statement runs a block only when its condition is true. Add else to give the false case its own block.

Learning objectives
  • Develop code to represent branching logical processes by using selection statements and determine the result of these processes.

One-way selection

The body runs only if the condition is true. Either way, the program continues after the if.

Code
int temp = 95;
if (temp > 90) {
  System.out.println("Heat warning");
}
System.out.println("Forecast done");
Output
Heat warning
Forecast done

Two-way selection

Exactly one of the two bodies runs.

Code
int score = 54;
if (score >= 60) {
  System.out.println("Pass");
} else {
  System.out.println("Retake");
}
Output
Retake

Braces matter

Without braces, only the next single statement belongs to the if, no matter how it's indented. A semicolon right after the condition creates an empty body, so the next block always runs.

Code
int x = 3;
if (x > 5)
  System.out.println("big");
  System.out.println("always printed");
if (x > 5); {
  System.out.println("also always printed");
}
Output
always printed
also always printed
Key points
  • Selection statements change which statements run.
  • One-way (if): the body runs only when true.
  • Two-way (if-else): one body runs when true, the other when false.
Watch out
  • Without braces, only the next statement belongs to the if. Indentation doesn't matter to Java.
  • A stray semicolon, if (x > 0);, makes an empty body.
Exam tip
  • In "what is printed" questions, mentally add braces to show exactly which statements each if controls.
Quick check
What is printed when n is 4?
if (n % 2 == 1)
  System.out.print("odd ");
System.out.print("done");
Show answer
done. Only the first print belongs to the if.