Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using final for the loop variable in enhanced for loop?

I understand how the below statement works.

for(final Animal animal : animalList){
//do some function
}

But what is the purpose of using the final keyword here ?

like image 830
Krithika Vittal Avatar asked Aug 02 '13 14:08

Krithika Vittal


4 Answers

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.

like image 78
Stephen C Avatar answered Oct 20 '22 13:10

Stephen C


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

like image 23
Tala Avatar answered Oct 20 '22 13:10

Tala


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.

like image 3
Chris Bode Avatar answered Oct 20 '22 13:10

Chris Bode


It's another java best practise.

The final declaration causes Java compilers to reject any assignments made to the loop variable.

When ever you have a chance, Declare all enhanced for statement loop variables final

like image 2
Suresh Atta Avatar answered Oct 20 '22 14:10

Suresh Atta