2

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
2
  • What is the error you are getting? Commented May 12, 2015 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 it links to also don't mention it, although all their examples match his first version, they don't rule out his second. Commented May 12, 2015 at 17:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

int i = 0;

3 Comments

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 no, local variables are not automatically initialized. But yes, this doesn't matter here.
Main.java:14: error: bad initializer for for-loop for(i : array) { ^ 1 error
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?

3 Comments

I understand that. I'm simply trying to understand the rationale behind the syntax.
Its the syntax. Thats the way it is. else how will java know that for given list the desired object
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.