前言
switch
在JDK12
之后,语法得到改善,不过JDK12
是预览属性,后面在JDK14
转正
switch语法
在JDK12
之前,switch
写法是这样
csharp
public class SwitchDemo {
public static void main(String[] args) {
int a = 1;
switch (a) {
case 1: {
System.out.println(1);
break;
}
case 2: {
System.out.println(2);
break;
}
default : {
System.out.println("aaa");
break;
}
}
}
}
但是JDK12
之后对switch
进行改进和预览,可以这么写
arduino
public class SwitchDemo {
public static void main(String[] args) {
int a = 1;
int data = switch (a) {
case 1 -> 1;
case 2 -> 2;
default -> throw new IllegalStateException("Unexpected value: " + a);
};
System.out.println(data);
}
}
也可以这么写
csharp
public class SwitchDemo {
public static void main(String[] args) {
int a = 1;
switch (a) {
case 1 -> {
a = a + 1;
System.out.println(a);
}
case 2 -> {
a = a + 2;
System.out.println(2);
}
default -> throw new IllegalStateException("Unexpected value: " + a);
}
;
System.out.println(data);
}
}
不用加break
总结
该switch
语法在JDK14
之后得到转正,新的 Switch 表达式允许在 switch 块中使用 ->
箭头符号来代替 case
和 break
关键字,使代码更加简洁明了