0

Consider the following Java code:

int[] array = {1, 2, 3, 4, 5, 6};
for(int i : array) {
    System.out.print(i + " ");
}

The above code obviously prints the contents of the array.

1 2 3 4 5

My question is why doesn't Java allow this?

int[] array = {1, 2, 3, 4, 5, 6};
int i;
for(i : array) {
    System.out.print(i + " ");
}

EDIT: when I compile the 2nd program, I get the following error:

Main.java:14: error: bad initializer for for-loop
        for(i : array) {
            ^
1 error
argo
  • 381
  • 1
  • 5
  • 15
  • What is the error you are getting? – GiantTree May 12 '15 at 17:07
  • @RüdigerHerrmann: That article doesn't address his problem at all --- it only covers the `Iterable` interface, specifically forgetting to `implements` it. The [Java 1.5.0 "For-Each Loop" docs](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html) it links to also don't mention it, although all their examples match his first version, they don't rule out his second. – Kevin J. Chase May 12 '15 at 17:35

3 Answers3

10

Because Java forces you to declare a variable here. The JLS, Section 14.14.2, defines the enhanced for loop with syntax:

EnhancedForStatement:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

EnhancedForStatementNoShortIf:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf

The UnannType is a type for the variable being declared.

It goes on to state that such an enhanced for loop is the equivalent of this, for looping over Iterables...

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

... and for arrays...

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

It's clear that the variable is a locally declared variable inside the loop.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

What is the error showing? Maybe you should initialize the varible:

int i = 0;
bugs2919
  • 371
  • 1
  • 8
  • Primitives are initialized automatically with "0". The `for`-loop also changes the value of that `int` right away, so initializing that variable does not change anything. – GiantTree May 12 '15 at 17:04
  • 2
    @GiantTree no, local variables are not automatically initialized. But yes, this doesn't matter here. – Tom May 12 '15 at 17:08
  • Main.java:14: error: bad initializer for for-loop for(i : array) { ^ 1 error – argo May 12 '15 at 17:08
0

You are using “Enhanced” for-loops. This is a feature available after Java 1.5. The syntax of enhanced for loop is

for(Object obj : List) {
    ...
}

If you write in other format it will throw a compilation error. Basically the code you wrote is syntactically incorrect. This will be a compilation error.

You can refer What is the syntax of enhanced for loop in Java?

Community
  • 1
  • 1
Partha Bisoi
  • 173
  • 2
  • 15
  • I understand that. I'm simply trying to understand the rationale behind the syntax. – argo May 12 '15 at 17:11
  • Its the syntax. Thats the way it is. else how will java know that for given list the desired object – Partha Bisoi May 12 '15 at 17:14
  • @ParthaBisoi From the original question, Java could infer the type from the initial variable declaration - int i; for(i : array) { . i is declared as an integer – committedandroider Oct 13 '19 at 16:21