Reputation: 531
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
Upvotes: 2
Views: 6774
Reputation: 173
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?
Upvotes: 0
Reputation: 178333
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 Iterable
s...
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.
Upvotes: 10
Reputation: 358
What is the error showing? Maybe you should initialize the varible:
int i = 0;
Upvotes: 0