zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Java13新特性 -- switch表达式

-- 特性 表达式 switch
2023-09-14 09:00:30 时间

引入了yield语句,用于返回值;

和return的区别在于:return会直接跳出当前循环或者方法,而yield只会跳出当前switch块。

@Test
public void testSwitch2(){
    String x = "3";
    int i = switch (x) {
        case "1" -> 1;
        case "2" -> 2;
        default -> {
        	yield 3;
        }
    };
    System.out.println(i);
}
@Test
public void testSwitch3() {
    String x = "3";
    int i = switch (x) {
        case "1":
        yield 1;
        case "2":
        yield 2;
        default:
        yield 3;
    };
    System.out.println(i);
}