在处理缩小转换的 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. ...
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
关于java - 算术赋值没有隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174713/