简体   繁体   English

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

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

byte b = 100 ; 

compiles without any errors, but 编译没有任何错误,但是

int i = 100 ; 
byte b = i ; 

throws an error. 引发错误。 Why? 为什么? Even when assigning 100 directly to b, we are assigning an int literal. 即使直接为b分配100,我们也将分配一个int文字。 So why did I get an error? 那么,为什么会出现错误?

byte b = 100 ;

Here 100 is a compile time constant. 这里100是编译时间常数。 And hence can be assigned to the byte . 因此可以分配给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 ; 

Now in this case, since i is not declared final , so it is no more a compile time constant. 现在在这种情况下,由于i没有声明为final ,因此它不再是compile time常数。 And in that case, you can later on come and modify the value of i , in between the initialization of i , and assignment of i to byte , as in the above case. 在这种情况下,您可以稍后修改 i的值,如上述情况那样,在assignment of i to byteinitialization of i assignment of i to byte之间。 Which will certainly fail. 这肯定会失败。 That is why compiler does not allow the assignment of i to byte type. 这就是为什么编译器不允许将i分配给byte类型的原因。

But, you can use an explicit casting for it to compile, which may of course crash at runtime. 但是,您可以对其使用显式强制转换,这当然可能在运行时crash By doing an explicit cast, you tell the compiler that - "I know what I'm doing, just do it for me". 通过执行显式强制转换,您可以告诉编译器-“我知道我在做什么,只为我做。” So, it will not bother about runtime behaviour of that casting, and will trust you that you are not doing anything wrong. 因此,它不会打扰该转换的运行时行为,并且会相信您没有做错任何事情。

So, either you can declare your int i as final , or you need to do the casting: - 因此,您可以将int i声明为final ,或者您需要进行强制转换:-

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

So, when you use a value 130 and cast it to byte , you pass through the compiler , but will certainly crash at runtime. 因此,当您使用值130并将其强制转换为byte ,您将通过compiler ,但肯定会在运行时崩溃。 And this is the problem that the compiler was trying to avoid. 这就是compiler试图避免的问题。


Now let's go back the first case: - 现在让我们回到第一种情况:-

byte b = 128;

The above assignment will now fail to compile. 上面的分配现在将无法编译。 Because even though the value 128 is a compile time constant, it is not big enough to fit in a byte , and that the compiler knows. 因为即使值128是一个编译时间常数,它也不足以容纳一个byte ,并且compiler知道。

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

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

i is not final and could have changed in the mean time. i不是最终的,在此期间可能已经改变。

Following would work: 以下将工作:

final int i = 100; 
byte b = i;

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

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