byte b = 0xFFFFFFFF; //OK, because integer -1 sits between -128 and 127, FINE!!
char ch = 0xFFFFFFFF; //Not OK, because integer -1 does not sit between 0 and 65535, FINE!!
byte b = 0L; //Compiler says Not OK? But long integer 0 sits between -128 and 127?
我不相信 java 编译器在上面代码的第三行中应用的缩小规则。
请帮助我理解这个缩小规则背后的逻辑。
最佳答案
文字 0L
上的 L
后缀使此文字成为 long
类型(64 位有符号整数)。
根据 Java 语言的规则,没有从 long
到 byte
的隐式缩小。
参见 Java 语言规范 section 5.2 Assignment Contexts :
In addition, if the expression is a constant expression (§15.28) of type
byte
,short
,char
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
注意常量表达式的类型不包括long
。
关于java - java中的隐式缩小规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30774042/