Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating final variables inside a loop

Tags:

java

final

is this allowed in java:

for(int i=0;i<5;i++){   final int myFinalVariable = i; } 

The keyword of my question is final. Is it allowed to do a final variable that changes with every run of the loop? I was wondering this because final says that you can't change the value of the variable (calling only myFinalVariable = i), but i'm redefining the whole variable with final int.

Are they two completely different variables just with the same name - with the variable from the previous run of the loop already heading down the road to the garbage collector?

like image 989
Jens Jansson Avatar asked Mar 04 '09 07:03

Jens Jansson


People also ask

Can I declare a variable inside a loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Can I use final in a for loop?

Adding final keyword makes no performance difference here. It's just needed to be sure it is not reassigned in the loop. To avoid this situation which can lead to confusions.

Can a final variable be declare inside a method?

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 Answers

Yes, it is allowed. The final keyword means that you can't change the value of the variable within its scope. For your loop example, you can think of the variable going out of scope at the bottom of the loop, then coming back into scope with a new value at the top of the loop. Assigning to the variable within the loop won't work.

like image 105
Greg Hewgill Avatar answered Oct 02 '22 22:10

Greg Hewgill