【发布时间】:2018-06-10 01:05:44
【问题描述】:
考虑下面的代码sn-p:
// automatic casting works for int to byte conversion as integer literal 127
// is in the range for byte
byte b1 = 127; //OK
// automatic casting doesn't work for long to int conversion
// even if long literal is in the range of int.
int i5 = 100L; // NOT OK - compilation error
对这种行为有什么解释吗?
为什么int转byte不需要显式转换,long转int需要显式转换?
How does Java convert int into byte? 的问题不同。这是关于int值超出范围时将int隐式转换为byte的问题。
【问题讨论】:
-
Java 不喜欢转换的丢失;它不知道没有真正的损失。
-
但是为什么在int到字节转换的情况下会这样呢?
-
@AniketSahrawat 同样是 int 和 byte..
-
更新问题更清晰:为什么在 int 到 byte 的情况下不需要显式转换,但 long 到 int 需要显式转换?
-
因为
127没有文字后缀,Java 能够将其转换为适当的类型。
标签: java