• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

declaring local variables final?

Ranch Hand
Posts: 223
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the advantage of declaring local variables (including method parameters) as final.
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When using local variables in an anonymous inner class, you are required to make them final. This is to do with the invisible accessor methods that get generated to implement the anonymous inner class.

In other cases, declaring local variables as final could sometimes have advantages like: -

  • Allows compiler to detect unintentional modification of a variable that is supposed to be constant
  • May allow Java compiler or Just In Time compiler to optimise code, knowing that the variable value will not change. This might give a small performance gain in a few circumstances.
  • May help maintenance of the program, by making it clear to the maintainer that the variable should not change

  • Unlike in C++, where "const" is used a lot, such uses of "final" are not common in Java.
    author and cow tipper
    Posts: 5000
    Hibernate Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Other than the obvious, that the values can't be changed, I'm guessing that there is a minor performance benefit, as the JVM can set the final variables off to the side, confident that the values will never change. I believe that is the case for class/instance level final variables, and for final methods as well.

    Is my hypothesis correct?

    -Cameron McKenzie
      Bookmark Topic Watch Topic
    • New Topic