if Statements
| English | Chinese | Pinyin |
|---|---|---|
| if statement | 条件语句 | tiáo jiàn yǔ jù |
Running code conditionally
- An if statement 条件语句 runs a block only when its condition is
true. if (score >= 60) { System.out.println("Pass"); }- If the condition is
false, the block is skipped entirely. - This is selection — the program chooses whether to run the block.
Adding else
- An
elseclause runs alternative code when the condition isfalse. if (score >= 60) { print("Pass"); } else { print("Fail"); }- Exactly one of the two branches runs — never both, never neither.
elseis optional; a bareifjust skips its block when false.
Braces group the block
- Braces
{ }group the statements that belong to theiforelse. - Without braces, only the single next statement is controlled by the
if. - Always use braces, even for one line — it prevents a common bug.
- Indent the block so the structure is visible at a glance.
Tracing the branch
- To trace an
if-else, evaluate the condition, then run the matching branch. - With
score = 75:75 >= 60istrue→ run theifblock → prints "Pass". - With
score = 40:40 >= 60isfalse→ run theelseblock → prints "Fail". - Only the code in the chosen branch executes.
Without braces, an if controls only the ONE statement right after it. So if (x > 0) a(); b(); always runs b() — the indentation lies. Always wrap the block in { }. And in an if-else, exactly one branch runs; you never fall through into both, unlike separate if statements.
Grading with if-else:
if (score >= 90) { grade = "A"; } else { grade = "B"; }score = 95→ conditiontrue→gradeis"A".score = 80→ conditionfalse→gradeis"B".
An if statement runs a block only when its condition is true; an optional else runs alternative code when it's false — exactly one branch executes. Use braces { } to group each block (without them, only the next single statement is controlled). Trace by evaluating the condition, then running the matching branch.
Which branch runs?
The first true condition's block runs; the rest are skipped.
In an if-else statement, how many of the two branches run?
Exactly one branch runs based on the condition.
if (score >= 60) prints Pass, else prints Fail. With score = 40, what prints?
40 >= 60 is false → the else block runs → Fail.
Without braces, an if statement controls only the single next statement.
Braces group the block; without them only one statement is conditional.
A bare if (no else) simply skips its block when the condition is false.
With no else, a false condition just does nothing.
The clause that runs when an if condition is false is the ___ clause (one word).
else provides the alternative branch.