switch的表达式必须是char, byte, short, int, Character, Byte, Short, Integer, String, or an enum类型, 否则会发生编译错误
switch语句必须满足以下条件,否则会出现编译错误:
与switch语句关联的每个case都必须和switch的表达式的类型一致。
如果 switch表达式是枚举类型, case 常量也必须是枚举类型.
不允许同一个switch的两个case常量的值相同.
和switch语句关联的常量不能为null.
一个switch语句最多有一个default标签.
When the switch statement is executed, first the Expression is evaluated. If the Expression evaluates to null, a NullPointerException is thrown and the entire switch statement completes abruptly for that reason.
public static void main(String[] args) {
String param = "t";
switch (param) {
case "a":
System.out.println("a");
break;
case "b":
System.out.println("b");
break;
case "c":
System.out.println("c");
break;
default:
System.out.println("default");
}
}
javap -c SwitchTest
对应的反汇编代码(稳住!!看不懂不要方,后面有个简化版):
Compiled from "SwitchTest.java"
public class com.chujianyun.common.style.SwitchTest {
public com.chujianyun.common.style.SwitchTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
Compiled from "SwitchTest.java"
public class com.chujianyun.common.style.SwitchTest {
public com.chujianyun.common.style.SwitchTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return