Why does this for/while loop instantiation fail to compile?
We get a compiler error when we declare a variable in a for/while loop without braces. For example,
public class XyzwsLoopDemo {
public static void main(String[] args) {
for (int x=0; x!=10; x++)
String str = "LOOP"; //Compiler Error
}
}
But it is fine when you add braces,
public class XyzwsLoopDemo {
public static void main(String[] args) {
for (int x=0; x!=10; x++) {
String str = "LOOP";
}
}
}
Let's look the definition of ForStatement in Java Language Specification:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForStatementNoShortIf:
for ( ForInitopt ; Expressionopt ; ForUpdateopt )
StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
The body of a ForStatement is a single Statement. Here is definition of Statement in Java Language Specification:
Statement:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
StatementWithoutTrailingSubstatement:
Block
EmptyStatement
ExpressionStatement
AssertStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
StatementNoShortIf:
StatementWithoutTrailingSubstatement
LabeledStatementNoShortIf
IfThenElseStatementNoShortIf
WhileStatementNoShortIf
ForStatementNoShortIf
The ForStatement expects a statement in its body, but the String str = "LOOP"; is a LocalVariableDeclarationStatement and is not a valid statement. The LocalVariableDeclarationStatement can appear in a block, a block of code with braces around it is, indeed, a "compound statement". Here is Block definition in JLS:
Block:
{ BlockStatementsopt }
BlockStatements:
BlockStatement
BlockStatements BlockStatement
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?