Java For Loop Example

Sharing is healthy !!

Hey guys!! Welcome to flower brackets blog. Today you will learn java for loop example and its types.

java For loop

For loop is used to repeat statements although the given condition is true. Condition is tested before executing the statements. For loop is better used in programming if the number of iterations is fixed.

Java For loop Syntax

for (initialization; termination; increment)
{
   statement(s).....
}

Java For loop flow diagram

Java For Loop Example

Remember following points before using for loop

Also Read – Do While Loop Java

  • Loop begins with an initialization expression which initializes the loop, and is executed only once.
  • Loop terminates if the termination expression evaluates to false.
  • After each iteration through the loop, increment expression is invoked.

Java For Loop 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


Java enhanced for loop or for-each loop

Now, we will learn the concept of enhanced for loop or for-each loop. For-each loop is designed to iterate through arrays and collections.

Also Read – Java If Else

This loop is very compact and easy to read since we do not need increment value and subscript notation.

For Loop Syntax

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

For Loop Example

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

Output:

Even Number: 2
Even Number: 4
Even Number: 6
Even Number: 8
Even Number: 10


Infinite For loop

For loop can be an infinite loop since the three expressions namely initialization, termination and increment are optional.

Infinite Loop Syntax

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

Infinite Loop Example

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……………. goes on

Sharing is healthy !!