Java – what is the purpose of using final for loop variables in an enhanced for loop?
I understand how the following statement works
for(final Animal animal : animalList){ //do some function }
But what is the purpose of using the final keyword here?
Solution
There are two possible reasons for this:
>It can simply avoid accidentally changing loop variables in the loop body (or record the fact that the loop variable will not be changed) > you can do this so that you can reference the loop variable in an anonymous inner class For example:
for(final Animal animal : animalList){ executor.submit(new Runnable(){ public void run() { animal.Feed(); } }); }
If the last content is omitted in this example, it is a compilation error
Updating it is not a compilation error in Java 8 and later Nonlocal variables now only need to be effectively finalized Simply put, this means that after initial declaration / initialization, the variable is not assigned to (using assignment operators or pre / post increment or decrement operators)