I was surprised to see that the following Java code snippet compiled and ran:
for(final int i : listOfNumbers) { System.out.println(i); }
where listOfNumbers is an array of integers.
I thought final declarations got assigned only once. Is the compiler creating an Integer object and changing what it references?
When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed.
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.
Final means a value cannot be changed. But when int[] myArray; is declared then myArray holds the reference of the array and not the values.
Imagine that shorthand looks a lot like this:
for (Iterator<Integer> iter = listOfNumbers.iterator(); iter.hasNext(); ) { final int i = iter.next(); { System.out.println(i); } }
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