背景与动机
流程控制决定程序执行路径。没有流程控制,程序只能从上到下一行行执行;有了条件和循环,程序才能根据输入、状态和规则做不同处理。
Java 常用流程控制可以分为两类:
- 分支:
if、switch - 循环:
for、while、do while

核心原理拆解
1. if 适合范围判断和复杂条件
int score = 85;
if (score >= 90) { System.out.println("A");} else if (score >= 60) { System.out.println("Pass");} else { System.out.println("Fail");}if 的条件必须是 boolean,不能像某些语言那样用 0 或非 0 代替真假。
2. switch 适合固定值匹配
int day = 1;
switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Unknown");}传统 switch 中如果不写 break,会继续执行后续分支,这叫穿透。
3. for 适合已知次数的循环
for (int i = 0; i < 3; i++) { System.out.println(i);}for 常用于数组、集合遍历,或者明确知道循环次数的场景。
4. while 适合条件驱动的循环
int count = 3;
while (count > 0) { System.out.println(count); count--;}while 更适合“只要条件成立就继续”的场景。
5. break 和 continue
break 结束整个循环:
for (int i = 0; i < 10; i++) { if (i == 3) { break; } System.out.println(i);}continue 跳过本轮循环,继续下一轮:
for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.println(i);}最小可运行代码示例
public class ControlFlowDemo { public static void main(String[] args) { int score = 72;
if (score >= 60) { System.out.println("pass"); } else { System.out.println("fail"); }
for (int i = 1; i <= 3; i++) { System.out.println("round " + i); }
int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Unknown"); } }}常见陷阱与错误示例
1. if 条件不能写成数字
错误示例:
if (1) { System.out.println("ok");}Java 的条件表达式必须是 boolean。
2. switch 忘记写 break
switch (day) { case 1: System.out.println("Monday"); case 2: System.out.println("Tuesday");}如果 day 是 1,这里会继续执行 case 2。传统 switch 里通常要显式写 break。
3. 循环条件永远不变化
错误示例:
int i = 0;while (i < 10) { System.out.println(i);}i 没有变化,会形成死循环。
面试高频问题
1. break 和 continue 有什么区别
break 直接结束循环,continue 只跳过当前这一轮,继续下一轮循环。
2. if 和 switch 怎么选
范围判断、复杂条件用 if;固定值匹配、分支较清晰时可以用 switch。
3. while 和 do while 的区别是什么
while 先判断再执行,do while 先执行一次再判断,所以 do while 至少执行一次。
一句话总结
Java 流程控制的核心是:if 管条件分支,switch 管固定值匹配,for 管明确次数循环,while 管条件驱动循环。