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