- 旧的写法:没有break,则匹配的case后⾯会⼀直输出, value类型 可以是 byte、short、int 、char、String 类型
# 案例1
public void testOldSwitch1(){
int i = 1;
switch(i){
case 0:
System.out.println("zero");
case 1:
System.out.println("one");
case 2:
System.out.println("two");
default:
System.out.println("default");
}
}
# 案例2
public void testOldSwitch2(int i){
switch(i){
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("default");
}
}
- 新的写法:使⽤箭头函数,不⽤声明break,会⾃动终⽌,⽀持多个值匹配,使⽤逗号分隔
public void testNewSwitch(int i){
switch(i){
case 0 -> {
System.out.println("zero");
System.out.println("这是多⾏语句");
}
case 1,11,111 -> System.out.println("one");
case 2 -> System.out.println("two");
default -> System.out.println("default");
}
}