FAQ

Java

JSP

Servlet


Advertisement



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.


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |