Java – why is there no exception in this byte?

I initialized a byte as follows:

byte b = (byte) 0b11110000000;

Since a byte is 8 bits in size, I expect it to throw some exceptions or errors, because this number should only be allocated to short or above It is also evaluated as - 124? Or could this be "normal" behavior? (no exception thrown, but variable overflow)?

Solution

You deserve - 128

When you explicitly convert int to byte, the lowest 8 bits will be obtained and the rest will be discarded

In your example, the lowest 8 bits are 10000000, and the decimal value of this number is - 128

Without explicit cast, the code will not compile because your assignment will result in information loss

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>