My question is how compile time constant works internally so we didn't get an error in Below statement.
final int a = 10;
byte b = a;
And why am I getting error in this statement.
int a = 10;
byte b = a;
1.For a binary operator ( '=' or '+'... ), the compiler uses a numeric promotion system. This promotes a "primitive type" lower than "int" like byte char and short to an "int" before performing the operation.
2.Then byte, char, short, accept an int value that is constant and fits their type size.
so the below will Compile :
final int int1 = 10;
byte byt1 = int1; /* int to byte and when compiling to bytecode byt1 is assigned 10 and not a variable int1 as it's a final constant.*/
this will not compile :
byte byt1 = 2;
byte byt2 = +byt1; /* int to byte but when compiling to bytecode byt1 is not assigned 2 as byt1 value might change at run time to a value larger than what byte can support so you get compiler error.*/
and this will not compile :
final long lng1 = 10;
byte byt2 = lng1; /* long type to byte. remember byte, char and short only accept int.*/