For loop in java

In this post we are going to learn for loop in java.

For loop in java with example

For loop is used when you have to repeat a task “n” number of times . That is, we know to print some statement.

Syntax

for(initialization; condition; increment/decrement)
{
   statement(s).....
}

for loop in java

For loop has four parts variable declaration, condition, statements and increment/decrement variable. Here’s the flow of for loop,

  • Loop begins with an initialization which initializes the loop, and is executed only once.
  • Then condition in for loop is evaluated. If condition is true then statements inside for loop is executed.
  • When condition is false, statements inside for loop do not execute and control gets transferred to statements after for loop.
  • After each iteration through the loop, increment/decrement is invoked and loop counter is updated.
  • Finally for loop control shifts to second step to evaluate the condition.

Example

public class ForLoop
{
   public static void main(String[] args)
   {
      for(int x = 1; x <= 5; x++)
      {
         System.out.println(x);
      }
   }
}

Output:

1
2
3
4
5


Enhanced for loop

Enhanced for loop traverse the elements or each element of an array sequentially. This loop is helpful in iterating array and collections.

Also read – java if else

Syntax

for(Type var: array)
{
   // code goes here
}

public class EnhancedForLoop
{
   public static void main(String[] args)
   {
      int num[] = {2,4,6,8,10};
      for(int even : num)
      {
         System.out.println(even);
      }
   }
}

Output:

2
4
6
8
10


Infinite for loop

Infinite for loop in java is called infinite, when condition inside for loop is always evaluated to true.

Syntax

for ( ; ; )
{
   // code goes here
}

public class InfiniteForLoop
{
   public static void main(String[] args)
   {
      for( ; ; )
      {
         System.out.println("Infinite for loop");
      }
   }
}

Output:

Infinite for loop
Infinite for loop
Infinite for loop
Infinite for loop
Infinite for loop…………….


Iterating an array using for loop

public class ForLoopArray 
{
public static void main(String[] args)
{
int arrNum[] = {6,26,25,15};
for(int a = 0; a < arrNum.length; a++)
{
System.out.println(arrNum[a]);
}
}
}

Output:

6
26
25
15