Samy
Samy

Reputation: 485

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++)

Upvotes: 8

Views: 4776

Answers (3)

edornd
edornd

Reputation: 461

Well, making it simple, the second one is a "special" for, it's actually a "for each". It always needs the variable declaration inside. Instead of explaining it badly, here you are the link to an older question about this, check it out: Why is declaration of the variable required inside a foreach loop

Upvotes: 2

Bobby
Bobby

Reputation: 471

This is just the syntax of a for each loop. You cannot use a variable defined within the for each loop outside of the loop itself. It is just how the language is defined.

https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Upvotes: 0

M A
M A

Reputation: 72854

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) {

Upvotes: 12

Related Questions