The for
loop in Java is a control statement that allows you to repeat a block of code a specified number of times. It is a looping construct that executes a block of code as long as a boolean condition is true.
The syntax for the for
loop in Java is as follows:
for (initialization; condition; increment) { // code to be executed }
Here, the initialization
expression is executed once before the loop starts. It is used to initialize variables that are used in the loop condition. The condition
is a boolean expression that is evaluated before each iteration of the loop. If the condition is true
, the loop body is executed; if it is false
, the loop terminates. The increment
expression is executed after each iteration of the loop and is used to update variables that are used in the loop condition.
Here is an example of how to use a for
loop in Java:
for (int i = 0; i < 10; i++) { System.out.println("i = " + i); }
In this example, the for
loop iterates 10 times and prints the value of i
to the console on each iteration. The output will be:
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9
You can also use the break
and continue
statements to control the flow of a for
loop. The break
statement terminates the loop and transfers control to the statement immediately following the loop. The continue
statement skips the rest of the current iteration and starts the next iteration.
Here is an example of how to use the break
and continue
statements in a for
loop:
for (int i = 0; i < 10; i++) { if (i == 5) { break; // terminate the loop when i is 5 } if (i % 2 == 0) { continue; // skip the rest of the current iteration when i is even } System.out.println("i = " + i); }
In this example, the for
loop iterates 10 times, but it terminates when i
is 5 and skips the rest of the current iteration when i
is even. The output will be:
i = 1 i = 3 i = 5