Why local variable make as final whether method argument or inside method.
private void add(final int a , final int b) {
final int c = 0;
}
Please anyone clarify.i am searching a lot but i did not find exact answer.
One reason is it prevents you inadvertently changing them. It's good practise since it'll catch some hard-to-spot coding mistakes.
The second reason is that if you're using inner classes, variables referenced from an outer scope need to be declared as final. See this SO answer for more detail.
The problem with final is that it means different things in different contexts. See this discussion for more info.
const in C++.Functional style uses final variables. This is one reason. Another one is closures.
Final variables are the only ones that can be used in closures. So if you want to do something like this:
void myMethod(int val) {
MyClass cls = new MyClass() {
@override
void doAction() {
callMethod(val); // use the val argument in the anonymous class - closure!
}
};
useClass(cls);
}
This won't compile, as the compiler requires val to be final. So changing the method signature to
void myMethod(final int val)
will solve the problem. Local final variable will do just as well:
void myMethod(int val) {
final int val0;
// now use val0 in the anonymous class
finalhas absolutely no consequence when adding it to parameters (well apart from the obvious ones that are true in every context).