Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use final inside a for each loop

Tags:

java

final

I have a small conflict with effective java. On one hand it strongly encourages to use final modifier. It also encourages to use foreach loop.

However I did not see any piece of code anywhere, which codes like this:

for (final element e : list) {
  // do whatever.
}

If element is not expected to change then using final appears to be good. Why is it not so common?

like image 919
JavaDeveloper Avatar asked Aug 10 '13 08:08

JavaDeveloper


People also ask

Can I use final in a 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.

Can we use final Inside method?

The method variable is scoped within a method's call life-cycle. The final modifier ensures that upon initialization, it cannot be re-initialized within the scope of the method of that call. So yes, per method call, that variable is made final.

Is there foreach loop in Java?

In this tutorial, we will learn about the Java for-each loop and its difference with for loop with the help of examples. In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

Can we use final with string?

String class is final. This means you can't inherit from it. The variable "name" is final, meaning that you can't change it to point to a different instance of String.


1 Answers

Usually developers leave the defaults and only add code when they need to. i.e. what ever is the shortest code to write is easier. Think of a lecture theatre and they ask you to raise your hands if you do something and then they ask you to raise your hands if you don't, about half the room won't vote at all.

IMHO The default should have been final and you would have a keyword var for values which can change. This way much more fields would be final.

In this particular case, I don't make local variables final on the basis that methods should be short enough that you can reason whether the variable is changed or not. If you can't easily work this out, your loop/method is too complicated.

For fields however, I do recommend making these final whenever possible, esp if they are not private, as it is not so easy to read all the code where it might be used.

like image 195
Peter Lawrey Avatar answered Sep 19 '22 08:09

Peter Lawrey