gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:26:47 26 4
gpt4 key购买 nike

如果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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com