Object creating statement in Java doesn't allow to use a single-line loop. Why?

前端 未结 4 1364
遇见更好的自我
遇见更好的自我 2020-12-11 01:03

The following program has no importance of its own. It just counts the number of objects created through the use of a for loop using a static field inside the class Counter

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 01:16

    To understand why this happens, you have to look at Java's Blocks and Statements syntax in the language specification.

    A ForStatement is defined as:

    ForStatement:
        for ( ForInitopt ; Expressionopt ; ForUpdateopt )
            Statement
    

    Statement is defined as:

    Statement:
        StatementWithoutTrailingSubstatement
        LabeledStatement
        IfThenStatement
        IfThenElseStatement
        WhileStatement
        ForStatement
    
    StatementWithoutTrailingSubstatement:
        Block
        EmptyStatement
        ExpressionStatement
        SwitchStatement
        DoStatement
        BreakStatement
        ContinueStatement
        ReturnStatement
        SynchronizedStatement
        ThrowStatement
        TryStatement
    

    Then, looking at Block:

    Block:
        { BlockStatementsopt }
    
    BlockStatements:
        BlockStatement
        BlockStatements BlockStatement
    
    BlockStatement:
        LocalVariableDeclarationStatement
        ClassDeclaration
        Statement
    

    You'll notice that, within this specification, LocalVariableDeclarationStatement is not valid unless it is in a block. But, because the ForStatement requires that it is followed by a statement, there MUST exist parenthesis in order to make the expression valid. As such, any local variable declaration would be invalid in the loop without the brackets.

提交回复
热议问题