What is the purpose of using final for the loop variable in enhanced for loop?
Solution 1
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.
Solution 2
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
Solution 3
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.
Solution 4
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
Related videos on Youtube
Comments
-
Krithika Vittal about 2 years
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 ?
-
Luiggi Mendoza almost 11 yearsIt just means that the variable
animal
can't be reassigned e.g.animal = new Animal(); //inside the loop code
. -
Learn More almost 11 years@Luiggi -> Will variable
animal
not be assigned a new reference on each iteration ? -
Luiggi Mendoza almost 11 years@LearnMore note the comment: inside the loop code.
-
Chris Bode almost 11 years@LearnMore The entire variable is redeclared for every iteration of the loop.
-
Learn More almost 11 yearsThanks for response. Answers by Tala and Kan clarify this more.
-
Luiggi Mendoza almost 11 years@LearnMore even if you don't mark the
Animal animal
asfinal
and reassign it inside thefor
loop, the value stored in theCollection
won't be modified since it's just a copy. With this as basis, StephenC is right by saying It could simply be a way to avoid changing the loop variable accidentally and also provides another reason none of the other answered considered.
-
-
Luiggi Mendoza almost 11 yearsI don't understand how an
Animal
can easily change toString
. And no, this doesn't answer the question. -
kan almost 11 years@LuiggiMendoza Sorry, it was typo. If he knows what final variables mean, then it is easy to understand. BTW, afair this is impossible to do in C# for example.
-
Luiggi Mendoza almost 11 yearsI don't find that as a Java best practice at all. If you think or know it is, please add a link that proves it.
-
Suresh Atta almost 11 years@LuiggiMendoza Where ever we have a chance to mark a something as
final
i'l simply go for it.Correct me if i'm wrong :) -
Luiggi Mendoza almost 11 yearsSo you think declaring the parameters on setters as
final
is a best practice at all? Also, your link doesn't provide a real difference between marking the variable asfinal
or not, note that you can use thecontinue
keyword in both examples and the behavior will be the same. -
kan almost 11 years@LuiggiMendoza The link: stackoverflow.com/questions/316352/…
-
Luiggi Mendoza almost 11 yearsI find the answer on the posted Q/A more appropiate.
-
Suresh Atta almost 11 years@LuiggiMendoza Yes,I believe in that statement.**where ever you have a chance**
-
Stephen C over 10 yearsThis is "a good idea" but not "best practice". Something only qualifies as best practice when most practitioners (i.e. most experienced Java developers) would agree that it is the best solution. IMO, most Java developers would NOT agree that you should declare loop variables final "whenever you have the chance".
-
Stephen C over 3 yearsPlease read No Best Practices ... and consider removing "best practice" from you vocabulary.