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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With