要了解为什么会发生这种情况,您必须查看语言规范中Java的Blocks和Statements语法。
ForStatement定义为:
ForStatement: for ( ForInitopt ; expressionopt ; ForUpdateopt ) Statement
声明定义为:
Statement: StatementWithoutTrailingSubstatement LabeledStatement IfThenStatement IfThenElseStatement WhileStatement ForStatementStatementWithoutTrailingSubstatement: Block EmptyStatement expressionStatement SwitchStatement DoStatement BreakStatement ContinueStatement ReturnStatement SynchronizedStatement ThrowStatement TryStatement
然后,查看Block:
Block: { BlockStatementsopt }BlockStatements: BlockStatement BlockStatements BlockStatementBlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement您会注意到,在此规范内,LocalVariableDeclarationStatement无效,除非它在一个块中。但是,由于ForStatement要求在其后加上一条语句,因此必须存在括号才能使表达式有效。这样,在没有括号的情况下,任何局部变量声明在循环中都是无效的。



