File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why do final variables not need a cast?

 
Nick Shrine
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why does:
int i = 100;
byte b = i;
not compile, wheras:
final int i = 100;
byte b = i;
does?
 
Layne Lund
Ranch Hand
Posts: 3061
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joel McNary
Bartender
Posts: 1824
Eclipse IDE Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic