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?
3 Answers
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.
-
but what is life of final , if I declare a bitmap as final in method , so is its life over when method calling is over or its life end with the package or program end– AHFSep 7, 2014 at 16:20
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.
-
1
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.
which is illegal specifically in Java by convention
- no, it isn't.