Reputation: 127
Can someone tell me why this is valid in Java:
for (int i= 1; i<11; i++){
Movie movie = randomMovie();
}
and this is not?
for (int i= 1; i<11; i++)
Movie movie = randomMovie();
I do not get it because to me it seems to be the exact same thing, but when I put the curly braces, it suddenly turns correct.
Upvotes: 1
Views: 70
Reputation: 718966
Because the Java grammar forbids the latter. The relevant grammar rules are:
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
Statement:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
StatementWithoutTrailingSubstatement:
Block
EmptyStatement
ExpressionStatement
AssertStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
Note that the above do not include LocalVariableDeclarationStatement
.
You can find the complete syntactic grammar for Java in JLS Chapter 19.
Hypothetical question for you. Supposing that the following code is valid Java:
for (int i = 1; i < limit; i++)
Movie movie = randomMovie();
System.out.println("The last movie is " + movie);
what is the scope of the movie
variable?
The answer is that is must go out of scope immediately1. Which makes it a useless declaration, and the usage in the println
call is a compilation error.
I believe that this is the reason that they specified the Java syntax to disallow this. The declaration is useless and most likely a mistake, and should be brought to the programmer's attention via a compilation error.
(By the same argument the declaration in
for (int i = 1; i < 11; i++){
Movie movie = randomMovie();
}
is also a mistake. But doing something about this in the language grammar would be difficult.)
1 - The alternative is not tenable. In a statically checked language like Java, you cannot have a situation where an in-scope variable only exists depending on an earlier execution path. That would the value of movie
be if limit
was zero?
Upvotes: 1
Reputation: 1333
Check if this works.
Movie movie = null;
for (int i= 1; i<11; i++)
movie = randomMovie();
Upvotes: 1