The for Keyword
The
for is Java keyword that is used to
execute a block of code continuously to accomplish a particular condition. The for
loop specifies the statements to be executed, exit condition, and initialization
variables for the loop. The exit condition is evaluated before the first
iteration of the loop. It starts a looping block.
This
statement consists of tree parts i.e. initialization, condition, and
iteration.
initialization : It is an expression that sets the value of the loop
control variable. It executes only once.
condition : This must be a boolean expression. It tests the loop
control variable against a target value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop
control variable. The increment statement
is executed after each execution of the body of the loop, before the condition
is evaluated for the next iteration.
The syntax
of declaring a for loop is:
for(initialization;
condition; iteration){ ??????
??????. |
For
example, a sample for loop may appear as follows:
for ( int c=0; c < 5; c++ ) { System.println("Iter=" +c); } } } |
In the above example, we have initialized the for loop by assigning the '0' value to i. The test expression, i < 5, indicates that the loop should continue as long as i is less than 5. Finally, the increment statement increments the value of i by one.
The
for keyword may not be used as identifiers i.e. you cannot declare a
variable or class with this name in your Java program. You can also use this
keyword for nested loop i.e. loop within loop.