To understand why this is happening, you should look at the Java Blocks and Statement syntax in the language specification.
A ForStatement is defined as:
ForStatement: for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
An operator 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 the block:
Block: { BlockStatementsopt } BlockStatements: BlockStatement BlockStatements BlockStatement BlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement
You will notice that in this specification, LocalVariableDeclarationStatement is not valid if it is not in a block. But, since ForStatement requires an operator to follow it, parentheses MUST exist there to make the expression valid. Thus, any declaration of a local variable would be invalid in a loop without parentheses.
JasCav Nov 16 2018-11-11T00: 00-11
source share