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.
- 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.
Codeint temp = 95;
if (temp > 90) {
System.out.println("Heat warning");
}
System.out.println("Forecast done");OutputHeat warning Forecast done
Two-way selection
Exactly one of the two bodies runs.
Codeint score = 54;
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Retake");
}OutputRetakeBraces 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.
Codeint x = 3;
if (x > 5)
System.out.println("big");
System.out.println("always printed");
if (x > 5); {
System.out.println("also always printed");
}Outputalways printed also always printed
- 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.
- 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.
- In "what is printed" questions, mentally add braces to show exactly which statements each if controls.
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.