为什么"短期三十= 3*10"是一项法律任务?

Cei*_*cko 101 java short type-promotion

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

short thirty = 10 * 3;
Run Code Online (Sandbox Code Playgroud)

short变量的合法分配thirty

反过来,这个:

short ten = 10;
short three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED
Run Code Online (Sandbox Code Playgroud)

以及:

int ten = 10;
int three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED
Run Code Online (Sandbox Code Playgroud)

不编译,因为如果没有按预期方式转换,则不允许int为a 赋值short.

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

The*_*ind 138

因为编译器本身10*3编译时替换为30 .因此,有效:short thirty = 10 * 3在编译时计算.

试着改变tenthreefinal short(使它们编译时间常数),并看看会发生什么:P

检查javap -v 两个verisions(10*3final short)的字节码.你将能够看到差别不大.

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

情况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   
Run Code Online (Sandbox Code Playgroud)

案例-2:

public static void main(String arf[])  {
   final short s1= 10;
   final short s2 = 3;
   short s = s1*s2;
}
Run Code Online (Sandbox Code Playgroud)

字节代码:

  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   
Run Code Online (Sandbox Code Playgroud)

案例-3:

public static void main(String arf[]) throws Exception {
     short s1= 10;
     short s2 = 3;
     int s = s1*s2;
}
Run Code Online (Sandbox Code Playgroud)

字节码:

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 
Run Code Online (Sandbox Code Playgroud)

在上述情况下,103从本地变量获取的s1s2

  • 喜欢`尝试改变十和三到最后的短暂运动:) (17认同)
  • 同样在枚举结构中.事实上,使用1 << 5之类的东西来实现位域枚举常量是惯用的. (4认同)
  • 有趣的是,这也意味着`case 10*3:`和类似在switch开关构造中是合法的. (3认同)

Bat*_*eba 18

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

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

如果ten并且three被标记将是另一回事final.