• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

why do final variables not need a cast?

 
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why does:
int i = 100;
byte b = i;
not compile, wheras:
final int i = 100;
byte b = i;
does?
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
This looks like a job for .... legal tender! It says so right in this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic