为什么 int/byte/short/long 可以在没有类型转换的情况下转换为 float/double,反之亦然
问题描述:
我的代码是这样的 --
My code goes like this --
public void abc{
long a=1111;
float b=a; // this works fine even though this is narrowing conversion
long c=b;// this gives compilation error
}
你能解释一下为什么会这样吗?
Can you explain why this is happening?
答
原因在JLS 5.1.2:它说:long 到 float 或 double 是一种扩大转换.
而 float 到 byte、short、char、int 或 long 是缩小转换.
这就是为什么float b=a;
在您的程序中运行良好,因为它正在扩大转换.
和long c=b;
显示编译错误,因为它是一个缩小转换.
The reason is specified in JLS 5.1.2:
It says that : long to float or double is a widening conversion.
Whereas, float to byte, short, char, int, or long is narrowing conversion.
That's why float b=a;
is working fine in your program , since it is widening conversion.
And
long c=b;
is showing compilation error since it is a narrowing conversion.