繁体   English   中英

给一个字节分配一个int和一个int文字之间的区别?

[英]difference between assigning an int and an int literal to a byte ?

byte b = 100 ; 

编译没有任何错误,但是

int i = 100 ; 
byte b = i ; 

引发错误。 为什么? 即使直接为b分配100,我们也将分配一个int文字。 那么,为什么会出现错误?

byte b = 100 ;

这里100是编译时间常数。 因此可以分配给byte

int i = 100 ; 
// i = i + 100;  // It's allowed to add this statement later on, 
                 // if `i` is not declared final. And hence, the next assignment
                 // will clearly fail at runtime. So, compiler saves you from it
byte b = i ; 

现在在这种情况下,由于i没有声明为final ,因此它不再是compile time常数。 在这种情况下,您可以稍后修改 i的值,如上述情况那样,在assignment of i to byteinitialization of i assignment of i to byte之间。 这肯定会失败。 这就是为什么编译器不允许将i分配给byte类型的原因。

但是,您可以对其使用显式强制转换,这当然可能在运行时crash 通过执行显式强制转换,您可以告诉编译器-“我知道我在做什么,只为我做。” 因此,它不会打扰该转换的运行时行为,并且会相信您没有做错任何事情。

因此,您可以将int i声明为final ,或者您需要进行强制转换:-

int i = 100 ;    // replace 100 with 130, and you will be surprised that it works
byte b = (byte)i ; 

因此,当您使用值130并将其强制转换为byte ,您将通过compiler ,但肯定会在运行时崩溃。 这就是compiler试图避免的问题。


现在让我们回到第一种情况:-

byte b = 128;

上面的分配现在将无法编译。 因为即使值128是一个编译时间常数,它也不足以容纳一个byte ,并且compiler知道。

byte b=100将被编译,因为字节的范围是-128至127

    int i = 100 ; byte b = 129 ;// would give a compiler error

i不是最终的,在此期间可能已经改变。

以下将工作:

final int i = 100; 
byte b = i;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM