creating final variables inside a loop

Jens Jansson picture Jens Jansson · Mar 4, 2009 · Viewed 26k times · Source

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?

Answer

Greg Hewgill picture Greg Hewgill · Mar 4, 2009

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.