无法从 int 转换为 byte

cannot convert from int to byte

我有一个相当简单但让我感到困惑的问题。 假设字节变量 a、b、c:

byte a = 5;
byte b = 3;
byte c = a + b; // wont compile

第 3 行无法编译,因为 - 我想 - Java 必须在幕后进行计算,计算结果是一个整数。没有显式转换,不能将整数传递给字节。所以应该提供 (byte)(a+b) 。但现在假设有第 4 行代码显式转换为整数 ...

c = (int) 8 ; // compiles

尽管字节变量 'c' 被显式转换为整数 ,但它 可以编译。 Java 如何处理这方面的...?

您没有看到的是 a+b运行-time 操作,而 byte b = (int)8;编译时操作。因此,在编译期间,编译器知道常量 8 可以放入一个字节中。因此,(int) 的显式转换被 忽略 。字节码有无(int).

没有区别

现在,在第一种情况下,如果两个字节变量都是 final(即常量),那么编译器将允许这样做:

public static void main(String[] args) {
    final byte a = 5; // constant
    final byte b = 3; // constant
    byte c = a + b; // WILL compile;

}

重点是byte是8位,int是32位整数值。因此,例如,当您将两个小于 127 的字节数相加时,这可以添加到超出字节范围的超过 127 的结果,并且默认情况下 Java 对几乎所有数字都使用 int。

JVM doc 说:

A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.

Line 3 wont compile because - I suppose - Java has to make a calculation behind the scenes and the outcome of the calculation is an integer.

正确。

But now assume there is a 4th line of code with an explicit cast to integer

c = (int) 8 ; // compiles

It compiles although the byte variabel 'c' is explicitly casted to integer.

因为您使用了文字值 8,并且编译器知道 8 适合 byte

更好的比较是:

c = (int)b;

...失败了。