- switch(表达式) ,表达式可接收类型如下:
- 基本数据类型(byte、short、char、int)
- 引用数据类型
- 枚举类型
- String字符串
- case后面只能是常量,不能是变量。
- switch语句不加break的话造成case穿透。(解释一下case穿透:古时候,皇帝每天晚上从后宫佳丽三千中挑选一位宠幸,其中某两位佳丽所在房间之间没有墙(此时发生case穿透),皇帝宠幸完一位后,直接去了另一位的房间。)
举点栗子:
public class test {
public static void main(String[] args) {
int x = 2;
int y = 3;
switch(x) {
default:
y++;
break;
case 3:
y++;
case 4:
y++;
}
System.out.println("y = " + y);
}
}
程序段输出为:y = 4
public class test {
public static void main(String[] args) {
int x = 2;
int y = 3;
switch(x) {
default:
y++;
case 3:
y++;
case 4:
y++;
}
System.out.println("y = " + y);
}
}
程序段输出为:y = 6
此段程度,default结束没有break,造成case穿透,分别执行了default、case 3:、case 4:中的y++;故y的最终输出为6