switch分支语句
- 能用于switch判断的类型有:byte,short,int,char,String和枚举类型。
- break的使用:结束switch分支语句,但是switch的外部代码依然执行。(如果case语句中少写了break,编译不会报错,但是会一直执行之后所有case条件下的语句而不再判断,直到default语句)。
a.不加break时的代码:
int week=1;
switch(week) {
case 1:
System.out.println("星期一");
case 2:
System.out.println("星期二");
case 3:
System.out.println("星期三");
case 4:
System.out.println("星期四");
case 5:
System.out.println("星期五");
case 6:
System.out.println("星期六");
case 7:
System.out.println("星期日");
default:
System.out.println("无效");
}
输出结果:
星期一
星期二
星期三
星期四
星期五
星期六
星期日
无效
b.加入break后的代码:
int week=1;
switch(week) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
case 3:
System.out.println("星期三");
case 4:
System.out.println("星期四");
case 5:
System.out.println("星期五");
case 6:
System.out.println("星期六");
case 7:
System.out.println("星期日");
default:
System.out.println("无效");
}
输出结果:
星期一
- return的使用:结束方法执行,即下面代码不执行。(return不能用于代码块)。
static void show() {
System.out.println("show方法");
return;
}
public static void main(String[] args) {
show();
System.out.println("main方法");
}
输出结果:
show方法
main方法
- 与if语句的区别:(switch比if性能高,能用switch的地方尽量用switch)
1.如果case后的是个范围,则只能用if
2.如果是long,Boolean等switch不能使用的数据类型时,只能用if