web analytics

Java For Loop

When we know that how many times a block of code to be executed the java for loop will be the choice.
When we do not know the exact number of iteration then while / do-while can be used.


for (initialization; condition check; increment/decrement) {
// statements to be executed

Initialization is done one time before starting the loop.
Condition is checked before every iteration of loop.
Increment / Decrement is done after every iteration of loop.


Following example will print values from 1 to 15 integers:

for (int i = 1; i < 15; i++) {


First statement (int i) creates a variable i of type integer and sets its value to 1 before starting the loop.
Second statement (i < 15;) checks the condition before each execution of loop. If the condition is true the code block will be executed other wise loop will be terminated and control will go to the statement after for loop.
Third statement (i++) increments the variable after each iteration of loop.

Increment / Decrement by a value other than 1

We can increment / decrement the index variable by any arbitrary number. In following example the index variable will be incremented by 3 after each iteration of loop.

for (int i = 0; i <= 10; i = i + 3) {