The keyword final can improve performance, when I design our project, I think if the field, method and class doesn't need to be inherited, I usually make them final, but shall i set the formal parameter of my method final too? I'm not sure...
Asked
Active
Viewed 89 times
0
-
There are no performance impacts, as the final keyword does not even end up in the bytecode. – C-Otto Jan 23 '18 at 10:26
-
if you are not going to modify the values of the parameter variables, It is a good programming practice to keep them final. It saves lot of trouble at run time. Especially when you are using a constructor say you are using this.value=value and you forgot to use this and it became value = value so programatically its correct but your logic breaks. If you make the passed value parameter final then it will throw execution at compile time only. Also since parameters are local they can be used in inner anonymous classes only if they are declared as final. So use final wherever possible. – Madie Jan 23 '18 at 10:34
1 Answers
1
Sometimes its nice to be explicit(for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches
public void setTest(String test) {
test = test;
}
if you forget the 'this' keyword on a setter the variable you want to set doesn't get set. However if you used the final keyword on the parameter then the bug would be caught at compile time.

SF..MJ
- 862
- 8
- 19
-
I saw this in the question "Why should I use the keyword “final” on a method parameter in Java? " . And I know that, I just want to know, if I need to set my formal parameter final too. For example, does it affect the performance too? – Reed Chan Jan 23 '18 at 10:38