从java14开始, switch语句有了一个很大的调整, 这就让swicth语句有了更多的操作和选择,在代码上,更加的简便灵活.
- switch 标准方式
- switch - > 用法:
- switch yield 用法:
标准模式
int flag = 3;
switch (flag){
case 0: System.out.println("The number is 0" ); break;
case 1: System.out.println("The number is 1" ); break;
case 2: System.out.println("The number is 2" ); break;
default: System.out.println("you are right" ); break;
}
switch - > 用法:
使用 - > 方法更加简单, 就不用使用 break 命令, 保证只有一种路径会被执行!
int flag = 3;
switch (flag){
case 0 -> System.out.println("The number is 0" );
case 1 -> System.out.println("The number is 1" );
case 2 -> System.out.println("The number is 2" );
default -> System.out.println("you are right" );
}
switch yield 用法:返回值
int flag = 2;
String ss;
ss = switch (flag){
case 0 -> "The number is 0" ;
case 1 -> "The number is 1" ;
case 2 -> {
String c = "The number is 2";
yield c;
}
default -> "you are right" ;
};
System.out.println(ss);
输出