Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Variable Outside Foreach Loop in Java

Can someone please enlighten me on the following matter:

public class Loopy {
    public static void main(String[] args)
    {
        int[] myArray = {7, 6, 5, 4, 3, 2, 1};

        int counterOne; 
        for (counterOne = 0; counterOne < 5; counterOne++) {
            System.out.println(counterOne + " ");
        }
        System.out.println(counterOne + " ");

        int counterTwo = 0; 
        for (counterTwo : myArray) {
            System.out.println(counterTwo + " ");
        }

    }

}

In the for-loop, we declare counterOne outside the loop and use it inside the loop. This is correct, so long as we don't use counterOne after the loop is completed.

In the foreach-loop, we also declare counterTwo outside the loop and then use it only inside the loop. However, an error is thrown in this case:

"Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol symbol: class counterTwo location: class package1.Loopy"

Can you help me understand why?

The only difference between the two, is that counterOne is initialized to zero, and then is assigned values incrementally (smaller than 5).

In the foreach loop, counterTwo is assigned one by one, each array item.

The program works if we make this adjustment in the second for loop: for(int counterTwo : myArray), while the first for works in both cases:

  1. the existing one
  2. for (counterOne = 0; counterOne < 5; counterOne++)
like image 1000
Samy Avatar asked Jun 05 '15 17:06

Samy


1 Answers

From this section of the Java Language Specification about enhanced for-loops:

The enhanced for statement has the form:

EnhancedForStatement:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

EnhancedForStatementNoShortIf:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf

Note that the type declaration UnannType must be present in the for loop. Therefore, you should write the loop as follows:

for (int z : x) {
like image 135
M A Avatar answered Oct 15 '22 18:10

M A