[toc] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html # switch ## switch 資料可以是: byte, short, int, char, String, enum 只要case符合, 就開始執行該case下寫的statement, 直到break退出 如果想要or的效果, 放兩行case即可。 default是最後什麼都不符合的case Example: ```java int i = 1; switch (i) { case 0: System.out.println("0"); case 1: System.out.println("1"); case 2: case 3: System.out.println("2 3"); default: System.out.println("default"); } ``` which prints: ```shell= 1 2 3 default ``` --- 可以拿來作成類似if-else的形式(每個case都break) ```java int i = 1; switch (i) { case 0: System.out.println("0"); break; case 1: System.out.println("1"); // 1 break; case 2: case 3: System.out.println("2 or 3"); break; default: System.out.println("default"); } ``` --- 到Java12+, 可以使用 `->` - `->` 跟 `:` 不能混用 - `->` 後寫一個statement ```java switch (i) { case 0 -> System.out.println("0"); case 1 -> System.out.println("1"); case 2, 3 -> System.out.println("2 or 3"); default -> System.out.println("default"); } ``` ## Enhanced Switch: switch可以回傳值 (只能使用`->`) Example: ```java int i = 1; String result; switch(i) { case 0: result = "zero"; break; case 1: result = "one"; break; default: result = "not-sure"; } ``` 可以寫成: ```java int i = 1; String result = switch(i) { case 0 -> "zero"; case 1 -> "one"; default -> "not-sure"; }; ``` --- # Yield 像是上述範例, 如果你除了return值, 還想要做一些其他的敘述, 就可以用yield。 Example: ```java int i = 1; String result = switch(i) { case 0: yield "zero"; case 1: yield "one"; default: System.out.println("why?"); yield "not-sure"; }; ``` 或是 ```java int i = 1; String result = switch(i) { case 0 -> yield "zero"; case 1 -> yield "one"; default -> { System.out.println("why?"); yield "not-sure"; } }; ``` ## 語法糖?! 從Java 7之後, switch開始支持String. ```java String str = "world"; switch (str) { case "hello": System.out.println("hello"); break; case "world": System.out.println("world"); break; default: break; } ``` 其實是... ```java String str = "world"; String s; switch((s = str).hashCode()) { default: break; case 99162322: if(s.equals("hello")) System.out.println("hello"); break; case 113318802: if(s.equals("world")) System.out.println("world"); break; } ```