为什么赋值'int constant - > byte variable'有效,但'long constant - > int variable'不是?

gst*_*low 4 java primitive casting

我有这段代码:

int i = 5l; // not valid (compile error)
byte b = 5; // valid
Run Code Online (Sandbox Code Playgroud)

你怎么看待这件事?

为什么?

ass*_*ias 8

这在JLS#5.2(分配转换)中定义:

如果表达式是byte,short,char或int类型的常量表达式(第15.28节),如果变量的类型是byte,short或char,则可以使用缩小的原语转换,以及常量表达式的值可表示变量的类型.

所以:

byte b = 5; //ok: b is a byte and 5 is an int between -128 and 127
byte b = 1000; //not ok: 1000 is an int but is not representable as a byte (> 127)
byte b = 5L; //not ok: 5L is a long (and not a byte, short, char or int)
int i = 5L; //not ok: i is not a byte, short or char
int i = 5; byte b = i; //not ok: i is not a constant
final int i = 5; byte b = i; //ok: i is a constant and b is a byte
Run Code Online (Sandbox Code Playgroud)

  • +1.您可以添加最后一个语句编译,因为`final`值是内联的. (2认同)