File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes why do final variables not need a cast? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why do final variables not need a cast?" Watch "why do final variables not need a cast?" New topic

why do final variables not need a cast?

Nick Shrine

Joined: Jul 17, 2003
Posts: 11
why does:
int i = 100;
byte b = i;
not compile, wheras:
final int i = 100;
byte b = i;
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.

Java API Documentation
The Java Tutorial
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

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.
I agree. Here's the link:
subject: why do final variables not need a cast?
It's not a secret anymore!