Reputation: 4677
As a rule, a final variable has to be initialized only once. No other initializations are permitted. If it is so then, what happens when a final variable is declared inside a method. Suppose the method which a final variable is declared within is invoked/called thrice, the declaration statement of that final variable within the method is executed thrice and the final variable should be initialized thrice which is illegal specifically in Java by convention. In such a scenario, how could the compiler maintain the final variable inside a method?
Upvotes: 19
Views: 16379
Reputation: 23443
The method variable is scoped within a method's call life-cycle.
The final modifier ensures that upon initialization, it cannot be re-initialized within the scope of the method of that call.
So yes, per method call, that variable is made final.
Upvotes: 17
Reputation: 46844
The local variable is only in scope for the duration of the method. The variable can be initialized once for each method scope.
You might want to read up on the stack vs the heap to learn about how the JVM holds data for a method.
Upvotes: 22
Reputation: 26574
The final declaration on the variable within the method ensures that the value of the variable won't change within the scope in which it is declared, which in this case is only the method.
Upvotes: 5