为什么我得到类型不匹配:无法从int转换为byte
问题描述:
class Test
{
public static void main(String[] args)
{
byte t1 = 111;
byte t2 =11;
byte t3 = t1+t2;
System.out.println(t1+t2);
}
}
在eclipse中显示错误无法从int转换为byte .Here是122,其范围在字节范围内。所以为什么我在这里收到此错误。
In eclipse it is showing error cannot convert from int to byte
.Here sum is 122 which range in the byte range.So why i am getting this error here.
提前致谢...
答
当您对字节进行数学运算时,Java会进行扩展(自动类型提升) )将字节(隐式上升)转换为整数这种情况。所以当你执行时
When you do mathematical operations on byte, Java do Widening( automatic type promotion) to byte(implicitly up casted) to integer this case. so when you perform
byte t3 = t1+t2; // t1+t2; will be evaluated as integer.
由于t1 + t2结果比字节宽,所以你需要将它向下转换为字节。
As t1+t2 result is wider than byte so you need to downcast it to byte.
删除编译错误。
byte t3 = (byte) (t1+t2); // typecast to byte
有关详细信息,请阅读 JLS 5.1.2
For more information please read JLS 5.1.2