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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.