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 ?
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 ?
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:
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.
It's another java best practise.
The
final
declaration causesJava
compilers to reject any assignments made to the loopvariable
.When ever you have a chance, Declare all enhanced for statement loop variables final
The code is a syntax sugar for this equivalent code:
I think it is answers the question.
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 referenceanimal
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.
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.
You could also need to use this variable in anonymous function inside the loop