Recap
An if statement is a selection statement: it changes the normal top-to-bottom flow by running a segment of code only when a Boolean expression is true.
| Form | Syntax | What runs |
|---|---|---|
One-way (if) |
if (cond) { A } |
A runs only if cond is true; otherwise nothing |
Two-way (if-else) |
if (cond) { A } else { B } |
A if cond is true, B if it is false: exactly one |
Two separate ifs |
if (c1) { A } if (c2) { B } |
A, B, both or neither, tested one after the other |
Key relationships
| Idea | Rule |
|---|---|
| Condition | A Boolean expression inside parentheses; no semicolon after it |
| Else | No condition; runs when the matching if condition was false |
| Braces | Body is the block; without braces only one statement belongs to the if |
| Trace | Write variable values, evaluate the condition, follow one path |
| Rejoin | After the chosen body, execution continues with the next statement |
| Boolean variable | if (isReady) is the same as if (isReady == true) |
Assumptions
- The condition is exactly true or false.
- Variables used in the condition have been assigned before the
if. - For
if-else, the two bodies cover the two possible outcomes of one decision.
Mistakes to avoid
- Putting a semicolon straight after
if (...). - Leaving off braces and trusting the indentation.
- Using two
ifs when you need anif-else(or the reverse). - Writing
=instead of==in the condition. - Forgetting that the second of two
ifs sees the values changed by the first. - Printing or returning inside only one branch and expecting a value in the other.
Worked mini-example
int stock = 3;
int order = 5;
if (order > stock) {
order = stock;
}
stock = stock - order;
Trace: order > stock is 5 > 3, true, so the body runs and order becomes 3. Then stock = 3 - 3 = 0. After the code, stock is 0 and order is 3. With order = 2 instead, the condition is false, the body is skipped and stock becomes 1. The if here adjusts a value before the next statement uses it, which is the most common job for a one-way selection.
Quick self-check
- How many bodies run in an if-else? Answer: exactly one.
- With
x = 8, what does this print?if (x > 5) { System.out.print("A"); } if (x > 7) { System.out.print("B"); }Answer: AB, because both conditions are true and the ifs are independent. - What does
int k = 1; if (k > 3); { k = 9; }leavekas? Answer: 9. The semicolon is the whole body, so the block always runs. - Rewrite
if (n < 0) { s = "neg"; } if (n >= 0) { s = "pos"; }as one statement. Answer:if (n < 0) { s = "neg"; } else { s = "pos"; }.
Full explanations and diagrams are in the Topic 2.3 study guide.