【问题标题】:No implicit casting for arithmetic assignment?算术赋值没有隐式转换?
【发布时间】:2019-03-15 02:28:40
【问题描述】:

在处理缩小转换的 JLS 5.2 中,它说:

另外,如果表达式是一个常量表达式(§15.28) 输入 byte、short、char 或 int:

如果类型为 变量是 byte、short 或 char,常量的值 表达式可以用变量的类型来表示。 ...

"In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying."

  byte a = 1; // declare a byte
  a = a*2; //  you will get error here

在第一个语句中,一个字节范围内的整数1被分配给字节a,并且存在隐式转换。

在第二个语句中,值为 1 的字节 a 乘以整数 2。由于Java中的算术规则,值1的字节a被转换为值1的整数。这两个整数相乘(1*2)的结果就是整数2。

为什么第二条语句没有隐式转换导致错误?

Main.java:14: error: incompatible types: possible lossy conversion from int to byte
  a = a*2; 

【问题讨论】:

    标签: java implicit-conversion


    【解决方案1】:

    因为在您的示例中,a*2 不是 constant expression

    如果a 引用constant variable,这将是一个常量表达式:

    final byte a = 1;
    byte b = a * 2; // compiles fine
    

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 2021-11-08
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      相关资源
      最近更新 更多