ThomasMX ThomasMX - 2 years ago 72
Java Question

java - why does this byte cause no exception?

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)?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download