Different bit offset behavior in java

I work with bit offsets in Java and have the following code snippet that works as expected:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

This gives the value 2as expected. If, however, I try to extract this into a method like this:

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 this method that causes this to fail?

+4
source share
3 answers

Since valueand shiftare compile-time constants in this passage:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

then the compiler builds its values ​​(replaces all occurrences valuewith shifttheir actual values 1) and can check before Runtime that the result value << shiftwill not lead to a loss of accuracy.


, :

private void shiftAndCheck(final byte value, final int shift) {
  byte result = value << shift;
}

, shift , .

, shiftAndCheck(1, 32);, byte.

+4

int

0
    private void shiftAndCheck(final byte value, final int shift) {
        byte result = (byte) (value << shift);
    }

As @Konstantin already said, it returns int, so either pass it in bytes or use it int result.

0
source

Source: https://habr.com/ru/post/1626520/


All Articles