What is the purpose of using final for the loop variable in enhanced 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.

 for(Animal animal : animalList){
       //do some function
       animal = anotherAnimal;
       // use animal variable here
    }

You could also need to use this variable in anonymous function inside the loop


It simply means that the value of animal cannot change once it is set by the for loop. This may be required if you're going to reference animal within an anonymous class at some point in the loop.

Even if it isn't explicitly needed, it is good practice to make variables that will not change final. It can help you catch mistakes, and makes the code more self-documenting.


There are two possible reasons to do this:

  • It could simply be a way to avoid changing the loop variable accidentally in the loop body. (Or to document the fact that the loop variable is not going to be changed.)

  • It could be done so that you can refer to the loop variable in an anonymous inner class. For example:

    for(final Animal animal : animalList){
        executor.submit(new Runnable(){
            public void run() {
                animal.feed();
            }
        });
    }
    

    It is a compilation error if you leave out the final in this example.

    UPDATE it is not a compilation error in Java 8 and later versions. The non-local variable is now only required to be effectively final. In simple terms, that means that the variable is not assigned to (using an assignment operator or a pre/post increment or decrement operator) after the initial declaration / initialization.