【问题标题】:Does numeric promotion apply to constants in Java? [duplicate]数字提升是否适用于 Java 中的常量? [复制]
【发布时间】: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 这是不同的,因为我问的是数字促销。链接的问题是直接询问有关投射的问题。

标签: java constants


【解决方案1】:

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

但是,编译器能够将生成的整数和缩小为一个短整数,因为:

如果表达式是字节类型的常量表达式(第 15.28 节), short、char 或 int ... 如果 变量是 byte、short 或 char,以及常量的值 表达式可以用变量的类型来表示。

in the JLS所述。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多