Pages Navigation Menu

Coding is much easier than you think

Why final variable in for-each loop does not act final?

Why final variable in for-each loop does not act final?

 

public class ForEachLoop
{
	public static void main(String[] args)
	{
		String[] vowels = { "a", "e", "i", "o", "u" };

		for (final String str : vowels)
		{
			System.out.println(str);
		}
	}
}

 
Since the String str is declared as final, this code should not compile. However, this is working fine, because internal the structure of for-each loop is actually just as show below:

 

public class ForEachLoop
{
	public static void main(String[] args)
	{
		String[] vowels = { "a", "e", "i", "o", "u" };

		for (int i = 0; i < vowels.length; i++)
		{
			final String str = vowels[i];
			System.out.println(str);
		}
	}
}

 
Therefore, str is a local variable and during each iteration of the loop a new different final local variable is created.
 

About Mohaideen Jamil