What difference that final makes between the code below. Is there any advantage in declaring the arguments as final.
public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){
return ....
}
public String changeTimezone(final Timestamp stamp, final Timezone fTz,
final Timezone toTz){
return ....
}
For the body of this method the
final
keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that usingfinal
in general whenever possible will speed things up but that's not the case in recent JVMs.Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil
BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.
In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment. It's considered sometimes a good coding practice.
As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.
This saves you from declaring another local final variable in the method body:
Extract from The final word on the final keyword
The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example
Suppose we have a method
In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.
And this is also one of the Java Coding Best Practices.