What can be in the parentheses of a Java for loop?
My question is about Java for statements, such as
for (int i = 0; i < 10; ++i) {/* stuff */}
What I don't understand is how much code / what kind of code I can put in parentheses (i.e. I have int i = 0; I < 10; I'm in my example) - I really don't understand the language used to describe it: http://java.sun.com/docs/books/jls/third_edition/html/statements.html#24588
Basically, my problem boils down to requiring bits in the translation specification to look like:
ForInit: StatementExpressionList LocalVariableDeclaration
Editor: Wow I think the real answer is "learn to read and understand the symbols used in JLS - it is used for some reason." Thank you for all your answers
Solution
Statementexpressionlist and localvariabledeclaration are defined elsewhere on the page I'll copy them here:
StatementExpressionList: StatementExpression StatementExpressionList,StatementExpression StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression
and
LocalVariableDeclaration: VariableModifiers Type VariableDeclarators VariableDeclarators: VariableDeclarator VariableDeclarators,VariableDeclarator VariableDeclarator: VariableDeclaratorId VariableDeclaratorId = VariableInitializer VariableDeclaratorId: Identifier VariableDeclaratorId [ ] VariableInitializer: Expression ArrayInitializer
It doesn't make much sense to follow grammar further; I hope it's easy to read
This means that you can use any number of statementexpressions (separated by commas) or localvariabledeclaration. In the forinit section Localvariabledeclaration can consist of any number of "variable = value" pairs, separated by commas and starting with their types
So this is legal:
for (int i = 0,j = 0,k = 0;;) { }
Because "int i = 0, k = 0" is a valid localvariabledeclaration This is legal:
int i = 0; String str = "Hello"; for (str = "hi",i++,++i,sayHello(),new MyClass();;) { }
Because all random content in the initializer conforms to statementexpressions
Since statementexpressionlist is allowed in the update part of the for loop, it is also valid:
int i = 0; String str = "Hello"; for (;;str = "hi",new MyClass()) { }
Did you start taking pictures?