gpt4 book ai didi

java - 如果在三元运算符中使用局部变量,为什么从 int 到 short 的缩小转换不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:24:14 27 4
gpt4 key购买 nike

以下代码行被编译器 (sun-jdk-8u51) 接受,没有任何警告或错误:

short b = true ? 1 : 1;

接下来的两行代码会导致编译错误(不兼容的类型:从 int 到 short 的可能有损转换):

boolean bool = true;
short s = bool ? 1 : 1;

为什么编译器无法执行相同的 narrowing conversion第二种情况下的原始整数 1?

最佳答案

如@aioobe 在评论中所述:

This is because in the first case, since true is a compile time constant, the whole expression is evaluated during compile time, so you basically have short b = 1; whereas in the second version, the compiler does not do the simplification for you, hence the error

在变量bool 的声明中添加final 使其成为常量变量,这也允许编译器按上述方式解释代码。

final boolean bool = true;
short s = bool ? 1 : 1;

参见 section 4.12.4

关于java - 如果在三元运算符中使用局部变量,为什么从 int 到 short 的缩小转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33650398/

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