tags:

views:

169

answers:

3

Possible Duplicate:
Why this is not compiling in Java?

In java, curly braces are optional for one line for loops, but I've found a case where it isn't allowed. For instance, this code:

for(int i = 0; i < 10; i++)
    Integer a = i;

won't compile, but if you add curly braces, like so:

for(int i = 0; i < 10; i++){
    Integer a = i;
}

it will. Why won't this code compile?

A: 

I wonder if it has anything to do with the fact that the following statement is compound?

for(int i = 0; i < 10; i++)
    Integer a;
    a = i;
darren
+11  A: 

Because it wouldn't make sense to declare a new variable in a single line statement as it goes out of scope immediately.

If you look at the definition of a statement in Java, it doesn't include a LocalVariableDeclarationStatement, whereas a block does.

Mark Byers
+8  A: 

If you don't have curly braces, you can't put in a variable declaration. (The variable would be useless)

See the specification. (A LocalVariableDeclarationStatement can only occur directly inside of a Block.)

SLaks