I'm working with bit shifting in Java and have the following piece of code that works as expected:
final byte value = 1;
final int shift = 1;
byte result = value << shift;
This produces the value 2
as expected. If however I attempt to extract this into a method like so:
private void shiftAndCheck(final byte value, final int shift) {
byte result = value << shift;
}
This results in a compilation error:
java: incompatible types: possible lossy conversion from int to byte
The question is what is it about the method that causes this to fail?
Since the value
and shift
are compile-time constants in this snippet:
final byte value = 1;
final int shift = 1;
byte result = value << shift;
then the compiler inlines their values (replaces all the occurrences of value
and shift
with their actual values of 1
) and can verify before Runtime that the result of value << shift
won't cause any loss of precision.
Meanwhile, for the second snippet:
private void shiftAndCheck(final byte value, final int shift) {
byte result = value << shift;
}
the compiler has no evidence that shift
will represent such value, which wouldn't cause loss of precision and that's why raises a compilation error.
If compilation was possible in this case, then you'd have been able to do shiftAndCheck(1, 32);
which would result in overflowing the byte
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With