java - 算术赋值没有隐式转换?

标签 java implicit-conversion

在处理缩小转换的 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

关于java - 算术赋值没有隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174713/

相关文章:

java - Hibernate 创建大量连接

java - Apache mina FtpServer 的客户端监听器

c++ - 这个循环是否隐式地将一个 int 转换为 size_t?

scala - 在 Scala 中,如何为 Java 中定义的类定义伴随对象?

java - RMI 服务器异常

Java .Class 文件更改字符串

c - 无符号类型和更大的有符号类型之间的隐式转换行为不一致

c++ - 为什么我的值从 int 转换为 char?

type-conversion - kotlin - 数字类型的自动转换

java - 如何将子图像从 Sprite 表获取到数组中