问题

如果short在算术运算中自动提升为int,那么为什么是:

short thirty = 10 * 3;

对theshort变量thirty的合法转让?

反过来,这个:

short ten = 10;
short three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED

以及:

int ten = 10;
int three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED

不编译,因为如果没有按预期方式转换,则不允许将a7757188​​12值分配给ashort

关于数值文字有什么特别之处吗?


#1 热门回答(136 赞)

因为编译器用30个atcompile timeitself替换10*3。所以,有效:short thirty = 10 * 3是在编译时计算的。

尝试更改tenthreetofinal short(使它们编译时间常量),看看会发生什么:P

对于两个测试(10*3final short),使用javap -v检查字节代码。你将能够看到差别不大。

好的,所以,这是不同情况下的字节代码差异。

案例-1:

Java代码:main(){短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

在上面的例子中,103取自局部变量s1s2


#2 热门回答(18 赞)

是的,文字案例有一些特殊情况:10 * 3将在编译时进行评估。因此,对于乘法文字,你不需要显式的(short)转换。

ten * three不是编译时可评估的,因此需要显式转换。

如果tenthree被标记为final,那将是另一回事。


#3 热门回答(0 赞)

以下answer添加了JLS部分以及有关此行为的一些详细信息。

根据JLS §15.2 - Forms of Expressions

某些表达式具有可在编译时确定的值。这些是常量表达式(§15.28)。


原文链接