Java Reference
In-Depth Information
Initialization
The initialization part of a
for
-loop statement can have a variable declaration statement, which may declare one
or more variables of the same type, or it can have a list of expression statements separated by a comma. Note that
the statements used in the initialization part do not end with a semicolon. The following snippet of code shows the
initialization part in a
for-loop statement
:
// Declares two variables i and j of the same type int
for(int i = 10, j = 20; ; );
// Declares one double variable salary
for(double salary = 3455.78F; ; );
// Attempts to declare two variables of different types
for(int i = 10, double d1 = 20.5; ; ); /* An error */
// Uses an expression i++
int i = 100;
for(i++; ; ); // OK
// Uses an expression to print a message on the console
for(System.out.println("Hello"); ; ); // OK
// Uses two expressions: to print a message and to increment num
int num = 100;
for(System.out.println("Hello"), num++; ; );
You can declare a new variable in the initialization part of a
for
-loop statement. However, you cannot re-declare
a variable that is already in scope.
int i = 10;
for (int i = 0; ; ); // An error. Cannot re-declare i
You can reinitialize the variable
i
in the
for
-loop statement, as shown:
int i = 10; // Initialize i to 10
i = 500; // Value of i changes here to 500
/* Other statements go here... */
for (i = 0; ; ); // Reinitialize i to zero inside the for-loop loop
Condition-expression
The condition-expression must evaluate to a
Boolean
value of
true
or
false
. Otherwise, a compiler error occurs. The
condition-expression is optional. If it is omitted, a
Boolean
value of
true
is assumed as a condition-expression, which
results in an infinite loop unless a
break
statement is used to stop the loop. The following two
for
-loop statements
result in infinite loops and they are the same:
Infinite loop I
for( ; ; ); // Implicitly condition-expression is true