Why do I get an error when
int i=123;
byte b=i;
But not in this case
final int i=123;
byte b=i;
byte datatype has a range from -128 to 127 and it requires very little memory (only 1 byte). It can be used in place of int where we are sure that the range will be very small. The compiler automatically promotes the byte variables to type int, if they are used in an expression and the value exceeds their range.
The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
You can declare and initialize a Byte variable by assigning it a decimal literal, a hexadecimal literal, an octal literal, or (starting with Visual Basic 2017) a binary literal. If the integral literal is outside the range of a Byte (that is, if it is less than Byte.
When you initialize a final
variable with a constant expression, it will become a compile-time constant. Essentially, when the code is compiled, it will just hardcode the value everywhere your variable is added. You can see this in the byte code:
0 bipush 123
2 istore_1 [i]
3 bipush 123
5 istore_2 [b]
As you can see, it pushes the value 123
directly into the byte
(same as byte b = 123
), and that is a valid value for a byte
. It would not work with a value that is outside the allowed range for bytes.
If the variable is not final
(or not initialized with a constant expression), then the compiler will see it as a normal variable, and normal rules for assigning are applied. Meaning that to assign an int to a byte it needs to be casted:
int i = 123;
byte b = (byte) i;
Which produces this bytecode:
0 bipush 123
2 istore_1 [i]
3 iload_1 [i]
4 i2b
5 istore_2 [b]
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