It’s a basic for
loop.
It is documented in the Java Language Specification, section 14.14.1. The basic for Statement:
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression {, StatementExpression}
Normally, you’ll see it like this:
ForInit: int i = 0 // LocalVariableDeclaration
Expression: i < 10
ForUpdate: i++ // StatementExpression
for ( int i = 0 ; i < 10 ; i++ ) {
// code
}
// mostly the same as:
int i = 0;
while ( i < 10 ) {
// code
i++;
}
Mostly the same, since the scope of i
is limited to the loop, and the continue
statement will go to the i++
statement, not directly back to the loop.
But as you can see, all 3 are optional, where ForInit
can be a statement list instead of a variable declaration, and Expression
defaults to true
.
ForInit: In.init() // StatementExpression
Expression: !In.empty()
ForUpdate: // not present
for ( In.init() ; !In.empty() ; ) {
// code
}
// same as:
In.init();
while ( !In.empty() ) {
// code
}
The Expression
defaulting to true
means that the following are the same. I personally prefer the first, since for (;;)
almost reads like “forever”.
for (;;) { // loop forever
// code
}
while (true) { // loop forever
// code
}
CLICK HERE to find out more related problems solutions.