Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compile time error in case of casting

Tags:

java

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?

like image 771
Anand Avatar asked Aug 30 '12 18:08

Anand


People also ask

How do I fix compile-time error in Java?

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.

What causes compile-time error in Java?

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.

Is class cast exception a compiler error?

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.

Is class cast exception a runtime error?

ClassCastException is a subclass of the RuntimeException class which means it is an unchecked, runtime exception [4].


2 Answers

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.

like image 150
corgichu Avatar answered Oct 19 '22 09:10

corgichu


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

like image 28
Buu Nguyen Avatar answered Oct 19 '22 09:10

Buu Nguyen