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;
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;
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]
Boolean, byte, short, int, long are all ints by default, all are ints, and can be assigned as long as they do not exceed their range of values
The variable modified by final is determined at compile time and cannot be changed.
Variables modified by final do not automatically change the type
final int i = 127;
byte b = i;
final int i = 128;
byte b = i; // There will be compilation errors