Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you assign an int to an Integer in a loop without curly braces? [duplicate]

Tags:

java

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?

like image 320
TwentyMiles Avatar asked Jan 07 '10 23:01

TwentyMiles


1 Answers

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.

like image 194
Mark Byers Avatar answered Oct 11 '22 18:10

Mark Byers