This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Performance and the fly likes declaring local variables final? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Performance
Reply Bookmark "declaring local variables final?" Watch "declaring local variables final?" New topic
Author

declaring local variables final?

hasan khan
Ranch Hand

Joined: Aug 04, 2003
Posts: 222

what is the advantage of declaring local variables (including method parameters) as final.


SCJP, SCWCD
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


    Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
    Cameron Wallace McKenzie
    author and cow tipper
    Saloon Keeper

    Joined: Aug 26, 2006
    Posts: 4967

    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


    Author of Hibernate Made Easy, What is WebSphere???, JSF 2.0 Made Easy and the SCJA Certification Guides
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: declaring local variables final?
     
    Similar Threads
    Final variables
    accessing variable of an outer class from an inner class
    java interview question
    SCJP 1.5 - Procedure for registration.
    use of local final variables