for loop in java

Let’s learn for loop in java.

for loop in java

for loop executes a block of statements until condition evaluates to true. Use for loop if you know the number of iteration is fixed.

Syntax

for(initialization; condition; increment/decrement)
{
   // body
}

For loop is a combination of three parts: initialization, condition and increment/decrement. Here’s the flow of for loop.

for loop in java

For loop example

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

Output:

1
2
3
4
5


Infinite for loop

In for loop the condition can be any valid java expression but should be of type boolean. Condition in for loop is optional. If this is empty then compiler will always place “true”. For example,

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

Output:

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


Looping an array using for loop

Here’s an example on looping array using for loop.

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


Nested for loop in java

Nested for loop is nothing but for loop inside another for loop. Let’s learn how nested for loop work?

In nested for loop we have to manage condition, which is very important. Because we have to see that inner for loop do not cross outer for loop.

NOTE: inner for loop executes faster than the outer for loop. Also we can have ‘n’ number of loops inside outer loop.

Now let’s see nested for loop in java example to create pattern as shown below.

class NestedForLoop 
{
   public static void main(String[] args) 
   {
      int a, b;
      for(a = 1; a <= 5; a++)
      {
         for(b = 1; b <= a; b++)
         {
            System.out.print(b + "\t");
         }
         System.out.println();
      }
   }
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Also read – ArrayList in java