基本类型
public class SwitchDemo01 {public static void main(String[] args) {// case 穿透char grade = 'B';switch (grade) {case 'A':System.out.println("优秀");break;case 'B':System.out.println("良好");break;case 'C':System.out.println("及格");break;case 'D':System.out.println("再接再厉");break;case 'E':System.out.println("挂科");break;default:System.out.println("未知等级");}}
}
JDK7的新特性,表达式结果可以是字符串
public class SwitchDemo02 {public static void main(String[] args) {String name = "王红";// JDK7的新特性,表达式结果可以是字符串!!!switch (name) {case "来了":System.out.println("来了");break;case "那你":System.out.println("那你");break;case "王红":System.out.println("王红");break;default:System.out.println("弄啥来!");}}
}
反编译查看SwitchDemo02 如何实现
public class SwitchDemo02 {public SwitchDemo02() {}public static void main(String[] args) {String name = "王红";byte var3 = -1;switch(name.hashCode()) {case 840641:if (name.equals("来了")) {var3 = 0;}break;case 949367:if (name.equals("王红")) {var3 = 2;}break;case 1168157:if (name.equals("那你")) {var3 = 1;}}switch(var3) {case 0:System.out.println("来了");break;case 1:System.out.println("那你");break;case 2:System.out.println("王红");break;default:System.out.println("弄啥来!");}}
}
https://www.bilibili.com/video/BV12J41137hu?p=37&spm_id_from=pageDriver