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

13,823

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

Share:
13,823

Related videos on Youtube

Krithika Vittal
Author by

Krithika Vittal

A learner as always ....

Updated on June 05, 2022

Comments

  • Krithika Vittal
    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
      Luiggi Mendoza almost 11 years
      It just means that the variable animal can't be reassigned e.g. animal = new Animal(); //inside the loop code.
    • Learn More
      Learn More almost 11 years
      @Luiggi -> Will variable animal not be assigned a new reference on each iteration ?
    • Luiggi Mendoza
      Luiggi Mendoza almost 11 years
      @LearnMore note the comment: inside the loop code.
    • Chris Bode
      Chris Bode almost 11 years
      @LearnMore The entire variable is redeclared for every iteration of the loop.
    • Learn More
      Learn More almost 11 years
      Thanks for response. Answers by Tala and Kan clarify this more.
    • Luiggi Mendoza
      Luiggi Mendoza almost 11 years
      @LearnMore even if you don't mark the Animal animal as final and reassign it inside the for loop, the value stored in the Collection 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
    Luiggi Mendoza almost 11 years
    I don't understand how an Animal can easily change to String. And no, this doesn't answer the question.
  • kan
    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
    Luiggi Mendoza almost 11 years
    I 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
    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
    Luiggi Mendoza almost 11 years
    So 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 as final or not, note that you can use the continue keyword in both examples and the behavior will be the same.
  • kan
    kan almost 11 years
    @LuiggiMendoza The link: stackoverflow.com/questions/316352/…
  • Luiggi Mendoza
    Luiggi Mendoza almost 11 years
    I find the answer on the posted Q/A more appropiate.
  • Suresh Atta
    Suresh Atta almost 11 years
    @LuiggiMendoza Yes,I believe in that statement.**where ever you have a chance**
  • Stephen C
    Stephen C over 10 years
    This 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
    Stephen C over 3 years
    Please read No Best Practices ... and consider removing "best practice" from you vocabulary.