java :Why the Local variable should be declared final

user663724 picture user663724 · Feb 8, 2012 · Viewed 16.2k times · Source

Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?

I am using PMD to see the code violations.

Inside a webService Method, I have this below code

public ServiceRequest getData()
{
Status status = new Status();
// code
}

What PMD is suggesting me is that, this local variable status could be declared as final.

My question is, making it final would result in any performance improvements or if not what benefits the code could get?

Answer

Nick Garvey picture Nick Garvey · Feb 8, 2012

Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23

  • clearly communicates your intent
  • allows the compiler and virtual machine to perform minor optimizations
  • clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."

This is also discussed in this question: Can excessive use of final hurt more than do good?