在Java5之前,switch(expr)中,exper只能是byte,short,char,int类型。java
从Java5开始,java中引入了枚举类型,即enum类型。面试
从Java7开始,exper还能够是String类型。markdown
switch关键字对于多数java学习者来讲并不陌生,因为笔试和面试常常会问到它的用法,这里作了一个简单的总结:学习
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 }