Java for loop

Today you will learn java for loop.

Java for loop example is one of the loops in java. For loop is used when you have to repeat a task “n” number of times . That is, we know to print some statement.

Also read – continue statement in java

For loop has four parts variable declaration, condition, statements and increment/decrement variable.

Syntax

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

java for loop

NOTE:

  • 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.

For loop in java with 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 or for each loop

For each loops are nothing but enhanced for loop. For each loop traverse the elements or each element of an array sequentially.

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 as true or just use two semicolons in for loop.

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

Related Posts