5 Minutes of Java (8. For loop)

For Loop Structure:

for(Initialization; Conditional Test; Update)
{
   Statements //inside the loop body
}
//statements after for loop

meaning:

  • The initialization statement is executed before the loop starts, and it is executed only once. It is commonly used to initialize the loop variable.
  • Conditional test is evaluated, if it is true, loop body will be executed. If it is false, the for loop is terminated, and the statement after the for loop will be run.
  • Update statement is executed after the loop body is executed. It is usually used to increment or decrement the loop variable.

Example:

for (int i = 0; i < 8; i++) {
   System.out.println(i);
}
System.out.println("done");

Output:

0
1
2
3
4
5
6
7
done

Common use of for loop:

  • When the number of iterations is known from the outset.