因为编译器在编译时本身会替换为 30。所以,有效地:在编译时计算。10*3
short thirty = 10 * 3
尝试更改 和 to(使它们成为编译时间常量),看看会发生什么:Pten
three
final short
检查字节码是否同时用于验证 ( 和 )。您将能够看到几乎没有区别。javap -v
10*3
final short
好的,所以,这是不同情况下的字节码差异。
案例 -1 :
Java Code : main() { short s = 10*3; }
字节码 :
stack=1, locals=2, args_size=1
0: bipush 30 // directly push 30 into "s"
2: istore_1
3: return
案例 -2 :
public static void main(String arf[]) {
final short s1= 10;
final short s2 = 3;
short s = s1*s2;
}
字节码 :
stack=1, locals=4, args_size=1
0: bipush 10
2: istore_1
3: iconst_3
4: istore_2
5: bipush 30 // AGAIN, push 30 directly into "s"
7: istore_3
8: return
案例-3 :
public static void main(String arf[]) throws Exception {
short s1= 10;
short s2 = 3;
int s = s1*s2;
}
字节码 :
stack=2, locals=4, args_size=1
0: bipush 10 // push constant 10
2: istore_1
3: iconst_3 // use constant 3
4: istore_2
5: iload_1
6: iload_2
7: imul
8: istore_3
9: return
在上面的情况下,并且取自局部变量和10
3
s1
s2