why does: int i = 100; byte b = i; not compile, wheras: final int i = 100; byte b = i; does?
posted 13 years ago
When the variable is final, the compiler can make some optimizations. In this case, it can detect that the value is small enough to still be stored as a byte rather than an int. When the int variable isn't final, then the compiler doesn't make that assumption. I don't know any specific reason why it can't. From my basic knowledge of compilers, though, it would be more complicated than in the case where the variable is final.
The compiler does not make that assumption be cause the compiler knows nothing about what will be going on at run time. In a multi-threaded environment, another thread could change the value of int i between the time it gets set to 100 and the time that byte b is assigned that value.
By making i final, the compiler knows that it cannot change. And since it's being set to a literal value, the compiler can substitute that literal value anywhere it sees the variable. Granted, if both are local variables, that's not an issue, but extra logic checks like that increase compilation time. I would be just as happy to not heve them, myself.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Do you pee on your compost? Does this tiny ad?
the new thread boost feature brings a LOT of attention to your favorite threads