Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - why does this byte cause no exception?

Tags:

java

primitive

I initialized a byte as follows:

byte b = (byte) 0b11110000000;

Since a byte is 8 bits of size, I was expecting that it would throw some exception or error, since this number should be assignable only to a short or above. Still it evaluated to -124? Or is this perhaps the "normal" behavior? (no exception thrown, but variable is overflown)?

like image 410
ThomasMX Avatar asked Mar 13 '26 00:03

ThomasMX


1 Answers

You should be getting -128.

When you explicitly cast an int to byte, the lowest 8 bits are taken, and the rest are discarded.

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

Without the explicit cast, the code won't pass compilation, since your assignment causes a loss of information.

like image 51
Eran Avatar answered Mar 15 '26 14:03

Eran