数字推广是否适用于Java中的常量?

时间:2018-05-02 10:30:42

标签: java constants

§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 short a = 2;
final short b = 3;
short s = a + b; // no error

为什么?规格的哪一部分解释了这个?

我的猜测是它们是编译时常量,因此被视为整数。

1 个答案:

答案 0 :(得分:5)

升级必须由编译器完成,因为there are no JVM instructions for addition of shorts

但是,编译器能够将得到的整数和缩小为short,因为:

  

如果表达式是byte类型的常量表达式(第15.28节),   short,char或int ...如果类型为,则可以使用缩小的基元转换   变量是byte,short或char,以及常量的值   表达式可以在变量的类型中表示。

in the JLS所述。

添加final确定它是否是常量表达式。