Java compile time error in case of casting

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?


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


Try this

int i=45;
final int j=i;
byte b=j;

Compare this with

final int j=56;
byte b=j;

this ll give you an idea how implicit narrowing of int to byte takes place ie it only takes place if the value assigned is a constant expression

链接地址: http://www.djcxy.com/p/73628.html

上一篇: 什么是不可改变的?

下一篇: 转换时出现Java编译时错误