Java For Loop

For loop in java is used to execute a set of statements multiple times until a condition becomes false. The for statement provides a compact way to iterate over a range of values.

For loop is recommended by programmers if you know how many times you want to iterate.

Here we are going to discuss two flavors of for loops:
  • Simple for loop.
  • For each for loop.

Simple For Loop in Java

Here is the syntax of simple for loop

for(initialization; condition; update) {
    /* code to be executed */
For Example:
for(a = 0; a < 10; ++a){

Above for loop prints integers from 0 to 9;

For loop consists of the keyword for followed by three statements separated by semicolon and enclosed in parentheses.

  • The Initialization statement will be executed first and only once. We can declare and initialize any number of loop control variables here.

  • Next, condition expression is evaluated. If the value of condition expression is true then code block of for loop will be executed otherwise the loop will be terminated.

  • After execution of the code block of for loop control goes to update statements of the loop statement which modifies the loop control variables.

  • Next, control again goes to condition expression.

  • For loop iteration will continue unless condition expression becomes false.

C For Loop Statement Control Flow Diagram

For Each For Loop in Java

For each form of for loop is used to iterate over Collections and Arrays. Here we don't have to worry about the number of elements in Collections or array. For each version of for loop is preferred over simple for loop to traverse collections and arrays as we don't have to do explicit increment/decrement of loop control variable.

Here is the syntax of simple for loop

for(Type var: Collections) {
    /* code to be executed */