先看如下java源代码
public int testSwitch(){
int i=3;
switch(i){
case 1: return 1;
case 2: return 2;
case 3: return 3;
default: return -1;
}
}
通过javap命令可以看到该源码被编码后的字节码如下:
0: iconst_3
1: istore_1
2: iload_1
3: tableswitch{ //1 to 3
1: 28;
2: 30;
3: 32;
default: 34 }
28: iconst_1
29: ireturn
30: iconst_2
31: ireturn
32: iconst_3
33: ireturn
34: iconst_m1
35: ireturn
java虚拟机使用tableswitch来处理switch语句
首先 push int constant 3
存储变量i,变量i是第一个,所以是istore_1 第0个是this
然后再加载i,进行tableswitch判断
当i是1时,将执行第28行,再执行29行退出
退出进将返回常量1,也就是iconst_1, 后面的一样