算术赋值没有隐式转换?

No implicit casting for arithmetic assignment?

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

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable. ...

"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; 

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

如果 a 引用 constant variable:

则它将是一个常量表达式
final byte a = 1;
byte b = a * 2; // compiles fine