【发布时间】:2018-10-12 10:24:53
【问题描述】:
§5.1.2 和 §5.6.2 没有提及数值提升和扩展如何对常量起作用。
以下给出了预期的错误:
short a = 2;
short b = 3;
short s = a + b; // error: incompatible types: possible lossy conversion from int to short
但是如果它们被声明为final,它编译不会出错:
final short a = 2;
final short b = 3;
short s = a + b; // no error
这是为什么呢?规范的哪一部分解释了这一点?
我的猜测是它们是编译时常量,因此被视为整数。
【问题讨论】:
-
关闭以查找副本。答案是:编译时constant expressions。
-
这应该可以工作
short s = (short) (a + b);没有最终的 a 和 b -
@T.J.Crowder 这是不同的,因为我问的是数字促销。链接的问题是直接询问有关投射的问题。