考虑以下代码片段:
// 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的问题。
最佳答案
扩大转换(例如 byte
到 int
)通常被 Java 编译器隐式接受,因为没有信息丢失(int
的范围大于 byte
的范围)。
缩小转换范围(例如 long
到 int
,如您的情况)会导致信息丢失,因此通常需要显式转换。
参见 this类似的问题,和this . Java Language Specification 的相关部分:
Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.
...
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.
A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
Byte and the value of the constant expression is representable in the type byte
Short and the value of the constant expression is representable in the type short.
Character and the value of the constant expression is representable in the type char.
(强调我的)
一些混淆源于我们特别处理常量表达式,因为我们使用的是数字文字。上述规范也需要仔细阅读。
清理一些东西并直接回答 OP 的一些查询:
为什么一种类型的缩小支持隐式缩小,而另一种不支持?
即。为什么
byte b1 = 127
隐式工作,而int i5 = 100L
不是吗?byte b1 = 127
执行隐式转换(参见上面引用中的粗体文本),“常量表达式的值可以用字节类型表示”。即127
由byte
表示,所以转换是隐式的。如果你尝试byte b1 = 128
,您将收到有关不兼容类型的错误,如128
不能用byte
表示.我们在这里完全允许隐式转换的唯一原因是因为我们使用的是常量表达式。我们没有在
int i5 = 100L
中进行隐式转换(即使 100 在int
的范围内)因为它根本没有在允许的隐式转换中列出(变量的类型int
不是byte
、short
或char
之一)。我们也没有在
byte a = 0L
中进行隐式转换, 这次常量表达式的类型是long
, 不是byte
类型,short
,char
, 或int
.
普通程序员如何知道隐式允许哪种收缩转换?
隐式缩小转换仅在您将常量表达式 分配给变量时发生。在这些情况下,隐式转换很好,因为我们不想编写像
byte b = (byte)0
这样的代码。每时每刻。同时,如果我们写类似byte b = 128
的内容,我们确实希望得到警告。 ,因为它没有直观的行为。当我们不分配常量表达式时(例如
int x = 0; byte b = x;
),我们总是希望在进行潜在有损转换时得到警告,因为它们很危险 - 因此在这种情况下显式转换也会感觉。
关于java - 为什么允许从 int 到 byte 而不是从 long 到 int 的隐式缩小转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48025164/