A program is a sequence of decisions. Control flow chooses which statements run. Java’s sequential statements, if, switch, and loops (next topic) are the whole story at the language level — there is no goto for you to use (the keyword is reserved).
Mental model: the condition is a boolean expression. Java does not treat 0 as false or null as false. That is C. A Boolean object unboxes and can NPE.
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else {
grade = "C";
}
else if is just else followed by an if. Order matters: first match wins.if (ready); { start(); } — the semicolon is a statement. start() always runs.// Incorrect — always prints
if (ok);
System.out.println("ok");
// Correct
if (ok) {
System.out.println("ok");
}
if (ready) over if (ready == true). Prefer if (!ready) over == false."quit".equals(cmd) never NPEs on cmd.!(a && b) is !a || !b. Rewrite until a reader can say it aloud.boolean should be named is/has/can, not check or getReady.// Incorrect
if (list.size() != 0) { }
if (flag == true) { }
// Correct
if (!list.isEmpty()) { }
if (flag) { }
Classic switch is a statement. Selectors: byte short char int and their wrappers, String, and enums. Not long, not boolean, not float.
switch (day) {
case 1:
name = "Mon";
break;
case 6:
case 7:
name = "Weekend";
break;
default:
name = "Other";
}
break, execution falls through into the next case. That is a feature for stacked cases and a defect everywhere else.default may sit anywhere; it runs when no case matches. Put it last.null selector: NullPointerException (classic switch on String/wrapper/enum).String name = switch (day) {
case 1 -> "Mon";
case 6, 7 -> "Weekend";
default -> "Other";
};
-> cases do not fall through. Multiple labels use a comma.default). Enums can be exhaustive without default.yield to produce the value (Java 14+). Do not write break value — that was a preview syntax.int n = switch (cmd) {
case "inc" -> {
log();
yield count + 1;
}
default -> count;
};
cond ? a : b is an expression. Use it for a value, not for two side-effecting procedures.
String label = n == 1 ? "item" : "items"; // Incorrect — hard to scan, hides exceptions String s = p != null ? p.name() : q.next().name();
if or a switch expression.cond ? 1 : 2.0 is double.if (ready = true) compiles and is always true.switch on String with mixed case — normalize or reject.if (obj) as if Java were JavaScript.Boolean condition that is null.boolean condition — never a number.else if from specific to general.break, return, or a commented intentional fall-through.~ Good luck with your revision! ~