We get a compiler error when we declare a variable in a for/while loop without braces. For example,
public class RedLoopDemo {
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 AbcdLoopDemo {
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:
Did you like the above article? Please share with your friends..
public class RedLoopDemo {
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 AbcdLoopDemo {
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 , StatementExpressionThe 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 ForStatementNoShortIfThe 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 StatementEvery 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.
Did you like the above article? Please share with your friends..
Comments
Post a Comment