问题描述
对于中级Java程序员来说,这听起来太微不足道了。但在我审查Java基础知识的过程中,发现了一个问题:
This may sound too trivial for an intermediate Java programmer. But during my process of reviewing Java fundamentals, found a question:
为什么缩小转换范围如下:
Why is narrowing conversion like:
byte b = 13;
将被允许而
int i = 13;
byte b = i;
会被编译器投诉吗?
推荐答案
因为字节b = 13;
是一个常量的赋值。它的值在编译时是已知的,因此编译器可以/应该/将会抱怨如果赋值的值会导致溢出(尝试 byte b = 123456789;
,看看是什么发生。)
Because byte b = 13 ;
is assignment of a constant. Its value is known at compile time, so the compiler can/should/will whine if assignment of the constant's value would result in overflow (try byte b = 123456789 ;
and see what happens.)
将它分配给变量后,您将分配表达式的值,尽管它可能是不变,编译器不知道。表达式可能导致溢出,因此编译器发出呜呜声。
Once you assign it to a variable, you're assigning the value of an expression, which, while it may well be invariant, the compiler doesn't know that. That expression might result in overflow and so the compiler whines.
这篇关于缩小类型转换:为什么允许将int赋值给声明中的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!