I stored integers in byte arrays but suddenly i got a "Required type: byte provided: int" error and some lines above not. So i tried to find out what different was, tests below:
byte b;
int integer = 12;
final int finalInteger = 12;
final int finalIntegerLO = 128; // 1000 0000
b = integer; //Required type byte provided int
b = finalInteger; //OK
b = finalIntegerLO; //Required type byte provided int
I guess having a final int with no '1' in the 2^7 place is Ok? It gave me an idea what happens if you combine it with bitwise operators and now it makes much less sense to me..
b = finalIntegerLO & 0xf; //OK
Is now ok.. but
b = integer & 0xf; //Required type byte provided int
not??
Can someone explain me why it acts so different?
Let's break every line
b = integer
Here we can see we are trying to convert int
into a byte
, so compiler asks as to explicitly typecast like so. (value of integer
may exceed byte range.)
b = (byte) integer;
b = finalInteger;
This case is slightly different since finalInteger
is a constant whose value is fixed and the compiler can tell beforehand whether it lies within the range of byte or not. If it lies within the range compiler is smart enough to convert int
to byte
without us to explicitly typecast it.
b = finalIntegerLO;
Range of byte is -128 to 127
clearly we cannot convert int to a byte and compiler sees that finalIntegerLO
is a constant so it is impossible to carry out this conversion and we see an error
To remove this error we can explicitly typecase (DONT DO IT THOUGH) which will give use as b = -128
b = (byte) finalIntegerLO;
b = finalIntegerLO & 0xf;
Here finalIntegerLO
and 0xf
both are constants and compiler can determine what will be the result it's 0
which is within the range of byte.
b = integer & 0xf;
Here integer
value can be changed before the execution of this line so the compiler is not sure if the result is within the range of int
or not, so it asks us to explicitly typecast like so.
b = (byte) (integer & 0xf);
Again like case 3 you may get an unexpected result.