switch關鍵字對於多數java學習者來說並不陌生,由於筆試和面試經常會問到它的用法,這里做了一個簡單的總結:
- 能用於switch判斷的類型有:byte、short、int、char(JDK1.6),還有枚舉類型,但是在JDK1.7后添加了對String類型的判斷
- case語句中少寫了break,編譯不會報錯,但是會一直執行之后所有case條件下的語句而不再判斷,直到default語句
- 若果沒有符合條件的case就執行default下的代碼塊,default並不是必須的,也可以不寫
1 package codeAnal; 2 3 public class SwitchDemo { 4 5 public static void main(String[] args) { 6 stringTest(); 7 breakTest(); 8 defautTest(); 9 } 10 11 /* 12 * default不是必須的,也可以不寫 13 * 輸出:case two 14 */ 15 private static void defautTest() { 16 char ch = 'A'; 17 switch (ch) { 18 case 'B': 19 System.out.println("case one"); 20 break; 21 case 'A': 22 System.out.println("case two"); 23 break; 24 case 'C': 25 System.out.println("case three"); 26 break; 27 } 28 } 29 30 /* 31 * case語句中少寫了break,編譯不會報錯 32 * 但是會一直執行之后所有case條件下的語句,並不再進行判斷,直到default語句 33 * 下面的代碼輸出: case two 34 * case three 35 */ 36 private static void breakTest() { 37 char ch = 'A'; 38 switch (ch) { 39 case 'B': 40 System.out.println("case one"); 41 42 case 'A': 43 System.out.println("case two"); 44 45 case 'C': 46 System.out.println("case three"); 47 default: 48 break; 49 } 50 } 51 52 /* 53 * switch用於判斷String類型 54 * 輸出:It's OK! 55 */ 56 private static void stringTest() { 57 String string = new String("hello"); 58 switch (string) { 59 case "hello": 60 System.out.println("It's OK!"); 61 break; 62 63 default: 64 System.out.println("ERROR!"); 65 break; 66 } 67 } 68 }