Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final variables inside a method in Java

Tags:

java

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?

like image 767
Bhavesh Avatar asked Oct 28 '11 02:10

Bhavesh


2 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.

like image 53
Cheryl Simon Avatar answered Sep 30 '22 11:09

Cheryl Simon


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.

like image 31
Oh Chin Boon Avatar answered Sep 30 '22 12:09

Oh Chin Boon