Java switch语句的穿透现象
·
Java switch 穿透现象
1. 什么是穿透
传统 switch-case 中,如果某个 case 末尾没有写 break;,程序不会跳出 switch,会顺序执行后面所有 case 的代码,不再判断 case 值,这就是 case 穿透。
2. 穿透演示代码
int num = 2;
switch (num) {
case 1:
System.out.println("数字1");
break;
case 2:
System.out.println("数字2");
// 缺少break,发生穿透
case 3:
System.out.println("数字3");
break;
default:
System.out.println("其他");
}
输出结果:
数字2
数字3
匹配到 case2 后,无 break,直接执行 case3 代码。
3. 穿透的作用(合理利用)
多个不同值需要执行相同逻辑时,省略 break 简化代码:
int month = 2;
switch (month) {
case 1:
case 2:
case 12:
System.out.println("冬天");
break;
case 3:
case 4:
case 5:
System.out.println("春天");
break;
}
1、2、12 都会输出冬天,利用穿透合并分支。
4. 注意事项
- 风险:不需要穿透时忘记 break,会出现逻辑bug;
- Java14+ 箭头
->写法不会穿透,无需写break,更安全:
int num = 2;
switch (num) {
case 1 -> System.out.println("1");
case 2 -> System.out.println("2");
case 3 -> System.out.println("3");
}
default后不加 break 也会穿透到下方case;- 只有传统
case:语法存在穿透,箭头语法无穿透。
更多推荐
所有评论(0)