Control flow 决定语句执行的顺序。Java 提供了条件语句(if、)、循环(、、)和分支语句(、、)— 以及现代增强功能,如 switch 表达式。
switchforwhiledo-whilebreakcontinuereturnif (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "F";
}
// ternary — concise if/else for a value
String status = (age >= 18) ? "adult" : "minor";
switch (day) {
case 1: name = "Mon"; break; // ⚠️ break needed — else it FALLS THROUGH
case 2: name = "Tue"; break;
default: name = "Unknown";
}
经典的 switch 需要在每个 case 之后使用 break — 忘记它会导致 fall-through(执行继续进入下一个 case),这是一个臭名昭著的 bug 来源。
// arrow syntax: no fall-through, returns a value, more concise
String name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 6, 7 -> "Weekend"; // multiple labels
default -> "Unknown";
};
现代 switch 表达式消除了 fall-through,可以返回值,而且更清晰 — 在新代码中更为推荐。
// for — known iteration count
for (int i = 0; i < 10; i++) { ... }
// enhanced for-each — iterate a collection/array
for (String item : items) { ... }
// while — condition checked BEFORE each iteration
while (condition) { ... }
// do-while — body runs at least ONCE (condition checked after)
do { ... } while (condition);
for (int i = 0; i < 10; i++) {
if (i == 5) break; // exit the loop entirely
if (i % 2 == 0) continue; // skip to the next iteration
}
return result; // exit the method
// labeled break — exit nested loops
outer:
for (...) {
for (...) {
if (found) break outer; // breaks BOTH loops
}
}
break 退出循环,continue 跳到下一次迭代,return 退出方法,标记的 break 可以一次性退出嵌套循环。
Control flow 是在任何程序中表达逻辑和决策的基本机制 — 每个非平凡的方法都使用它。
理解这些构造及其细微差别是必需的:switch fall-through 陷阱(以及更安全的现代 switch 表达式)、while 和 do-while 之间的区别(至少运行一次)、用于清晰集合迭代的 for-each,以及分支语句(包括用于嵌套循环的标记 break)。
掌握这些 — 并优先使用现代、更不容易出错的形式(switch 表达式、for-each)— 是编写正确、可读的 Java 逻辑和避免常见 control-flow bug 的基础。