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
case 1:
Here we can see we are trying to convert
intinto abyte, so compiler asks as to explicitly typecast like so. (value ofintegermay exceed byte range.)case 2:
This case is slightly different since
finalIntegeris 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 convertinttobytewithout us to explicitly typecast it.case 3:
Range of byte is
-128 to 127clearly we cannot convert int to a byte and compiler sees thatfinalIntegerLOis a constant so it is impossible to carry out this conversion and we see an errorTo remove this error we can explicitly typecase (DONT DO IT THOUGH) which will give use as
b = -128case 4:
Here
finalIntegerLOand0xfboth are constants and compiler can determine what will be the result it's0which is within the range of byte.case 5:
Here
integervalue can be changed before the execution of this line so the compiler is not sure if the result is within the range ofintor not, so it asks us to explicitly typecast like so.Again like case 3 you may get an unexpected result.