Java13新特性 -- switch表达式


引入了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);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM