Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "final int i" work inside of a Java for loop?

Tags:

java

final

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?

like image 673
Abe Avatar asked Oct 12 '10 01:10

Abe


People also ask

What does final int do in Java?

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.

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

What does final int do?

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.


1 Answers

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);     } } 
like image 143
Travis Gockel Avatar answered Sep 25 '22 01:09

Travis Gockel