The below code gives me compile time error Type mismatch: cannot convert from int to byte
int i = 10;
byte b = i;
but the below doesn't
final int i = 10;
byte b = i;
I don't understand why compiler is behaving in case of final?
If the brackets don't all match up, the result is a compile time error. The fix to this compile error is to add a leading round bracket after the println to make the error go away: int x = 10; System.
Compile-time errors occur when there are syntactical issues present in application code, for example, missing semicolons or parentheses, misspelled keywords or usage of undeclared variables. These syntax errors are detected by the Java compiler at compile-time and an error message is displayed on the screen.
If the program were compiled and the program run, every evaluation of this expression would throw a ClassCastException. There- fore, this is expression is deemed a compile-time error, a syntax error, and the expression will not be compiled.
ClassCastException is a subclass of the RuntimeException class which means it is an unchecked, runtime exception [4].
I think it's because 10 fits in a byte, but if the integer was something that takes more than 8 bits then it wouldn't be able to properly do this assignment anymore.
Edit
To clarify, making it final is allowing the compiler to treat the int as a constant so it can do constant folding. It's probably preventing the assignment with the non-final int because it doesn't know that value at compile time and it could be way bigger than what a byte can hold.
Case 1: compile error because an int
might not fit into a byte
; an explicit cast is necessary
Case 2: the compiler compiles the 2nd statement to byte b = 10;
(as i
is final
), so no error
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