Have a look at the Java language specification for the for
statement. You can declare and initialize any type of variable in a for
loop, and can even declare multiple variables, so long as they're all the same type. The relevant productions in the grammar are:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
LocalVariableDeclaration:
VariableModifiersopt Type VariableDeclarators
VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator
This means that you can do any of the following, e.g.,
for ( ; … ; … ) // no variable declaration at all
for ( int i; … ; … ) // variable declaration with no initial value
for ( int i=0; … ; … ) // variable declaration with initial value
for ( int i=0, j=1; … ; … ) // multiple variables
for ( final Iterator<T> it = …; … ; … ) // final variable
The first example there shows that you don't need any variables at all, and as pointed out in the comments, you don't have to have a ForUpdate
either. The only constraint is that you must have an expression in the middle, and it needs to be a boolean valued expression.
As an aside, the ForInit
can also be a StatementExpressionList
, which means that instead of declaring and initializing variables, you can also just execute some statements. E.g, you could do this (but this isn't a particularly useful example):
for ( System.out.println( "beginning loop" ; … ; … )
This could be useful, I suppose, in simulating a do/while
loop (if you wanted to do that), if the body is a simple function call:
for ( method() ; condition ; method() );