java - 为什么 "short thirty = 3 * 10"是合法分配?

标签 java short type-promotion

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

short thirty = 10 * 3;

short 变量 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

无法编译,因为如果未按预期进行强制转换,则不允许将 int 值分配给 short

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

最佳答案

因为编译器在 编译时 本身将 10*3 替换为 30。因此,实际上: short 30 = 10 * 3 是在编译时计算的。

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

使用 javap -v 为两个版本(10*3final 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 

在上述情况下,103取自局部变量s1s2

关于java - 为什么 "short thirty = 3 * 10"是合法分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32203462/

相关文章:

c - C 中的波浪号运算符

c - 在C中将int转换为short

java - 字节加法转换为int是因为java语言规则还是因为jvm?

java - 使用 java、eclipse 和 ant 自动复制构建的文件和库

java - 异常后继续列表迭代

java - CompletableFuture 异常处理程序链

java - 我怎样才能在java中将通用函数参数设置为protobuf?

将 Long 转换为 Unsigned Short Int/Strtol

c++ - 如何像内置类型一样提升两个模板类型进行算术运算呢?

haskell - 对类型维度的抽象