Java For Loop Syntax and Example

Free Java courses with 37 real-time projects - Learn Java

In this article, we are going to focus on Java for loop.

A loop is anything that is done repetitively.

Take an example of your daily routine, you wake up, you brush, have a bath, and then set off for work. You repeat this every day.

Your brain performs these functions automatically without you realizing it. This concept of performing a set of tasks repetitively is looping.

Whenever you know the exact number of times a particular set of programs is to be performed, you use for loop in java.

Java For loop

In Java, “for loops” are loops that run for a predetermined number of times. The for loop in Java follows a particular pattern. It contains the following parts

  1. The initialization
  2. The condition
  3. The increment/decrement
  4. The statements.

Syntax

for(control_variable initialize value; condition for control_variable;Increment or decrement control variable)
{
    //Loop Body
}

Control Flow of Java For Loop

The loops in java follow a particular pattern for execution.

1. Initialization – This process primarily focuses on initializing or providing initial values to a variable. This is the first step in the looping process.

2. Checking condition – As the name suggests, after the variable is initialized, it checks whether the value satisfies the condition of the loop.

Once the condition evaluates to true, the content inside the loop starts to execute. However, if the condition evaluates to false, the control shifts outside the loop.

3. Loop Body – The next step in execution is the body of the loop. There is a common misconception about the fact that the increment or decrement happens after the condition is checked.

But this is wrong as the control shifts to the body of the loop as soon as the condition of the loop evaluates to true.

4. After all the lines inside the body of the loop are executed perfectly, the control shifts to the increment/decrement section.

Here the value of the counter gets modified and the loop continues.

Flowchart of the control flow of for loop in Java

Flowchart of control flow of a for loop in Java

Java program to understand the concept of for loops in Java

package com.dataflair.javaforloop;

public class JavaForLoop
{
public static void main(String[] args) 
{
        
        System.out.println("We will be learning about for loops");
        int i;
        for(i=0;i<5;i++)
        {
            System.out.println("Currently in Loop. value of i = "+i);
        }
        
        System.out.println("Currently outside Loop. value of i = "+i);
    }
}

Output:

We will be learning about for loops
Currently in Loop. value of i = 0
Currently in Loop. value of i = 1
Currently in Loop. value of i = 2
Currently in Loop. value of i = 3
Currently in Loop. value of i = 4
Currently outside Loop. value of i = 5

Java program to iterate an array using for loop

package com.dataflair.javaforloop;
import java.io.*;

public class ArrayTraverse{

     public static void main(String []args)
     {
        int arrp[] = {1,2,3,4,5,6};
        for(int i=0;i<arrp.length;i++)
        {
            System.out.println("The "+(i+1)+" element is "+arrp[i]);
        }
     }
        
     
}

Output:

The 1 element is 1
The 2 element is 2
The 3 element is 3
The 4 element is 4
The 5 element is 5
The 6 element is 6

Enhanced For Loops(For-each loops) in Java

In java, there is a certain type of a “for loop” that enables you to traverse through any collection. This is a “for each” loop.

However, there is a catch. You cannot edit any value as the object used for traversing in an enhanced loop is immutable.

In normal for loops, you could alter the value inside the loop, but in enhanced for loops, you can only view the data. You cannot change it.

According to Java docs, the syntax of Enhanced for loops is as follows.

for( T object : Collection)
{
    //Code to be executed in the loop
}

Java program to illustrate the concept of enhanced for loops

package com.dataflair.javaforloop;

import java.util.*;
public class EnhancedForLoop
{
  public static void main (String[]args)
  {
        ArrayList<Integer>values=new ArrayList<>();
        for(int variable=10;variable<=50;variable+=10)
        {
            values.add(variable);//Adding the elements in the list. 
        }
        System.out.println("Now we will use the for each loop to print the elements in the ArrayList");
        for(Integer i:values)
        {
            System.out.print(i+" ");
        }
  }
}

Output:

Now we will use the for each loop to print the elements in the ArrayList
10 20 30 40 50

Infinite For Loop

An infinite “For loop” is a loop that runs indefinitely. You can make a for loop run infinitely in many ways.

Let us see an example of Java Infinite For Loop:

for(i=13;i>=10;i++)
{
//These statements run infinitely
}

We can observe that the value of “i” starts with 13 and keeps on increasing. This loop never stops.

Infinite for loops is something that may happen due to a flawed logic.

However, sometimes infinite loops are also purposefully added in code to serve some kind of a continuously executing function.

Java Nested For loop

The term nested for loop simply means a for loop inside another for loop. It is pretty simple to understand.

For each iteration of the outer for loop, the inner for loop executes a fixed number of times.

This nested for loop allows us to print patterns in Java.

A simple example of a pattern is given below.

package com.dataflair.javaforloop;

import java.io.*;

public class NestedPattern{

     public static void main(String []args)
     {
        int arrp[] = {1,2,3,4,5,6};
        for(int i=0;i<arrp.length;i++)
        {
            for(int j=0;j<i;j++)
            {
                System.out.print("*");
            }
            System.out.println("");
            
        }
     }
        
     
}

Output:

*
**
***
****
*****

Java Labelled For Loop

There are often times when we need to use nested loops in Java and thus need to break the outer loop instead of the inner loop. This can be made possible by Java Labels for For Loops.

We can label each and every for loop in Java. However, they are particularly useful when we need to continue or break a specific loop.

Confused? Do not worry. Let us take a look at an example.

Java program to illustrate the use of Labelled For loops

package com.dataflair.javaforloop;
public class LabelledForLoops {
    public static void main(String[] args) {
        
        int i,j;
        System.out.println("Let us see an example where we use nested loops without labels. ");
        for(i=1;i<=5;i++)
        {
            for(j=1;j<=5;j++)
            {
                System.out.println(i+" "+j);
                if(i==j)
                break;
            }
            System.out.print("\n");
        }


        System.out.println("Now let us see the difference when we use labels. ");
        aa:
        for(i=1;i<=5;i++)
        {
            bb:
            for(j=1;j<=5;j++)
            {
                System.out.println(i+" "+j);
                if(i==j)
                break aa;
            }
            System.out.print("\n");
        }
    }
    
}

Output:

Let us see an example where we use nested loops without labels.
1 12 1
2 23 1
3 2
3 3

4 1
4 2
4 3
4 4

5 1
5 2
5 3
5 4
5 5

Now let us see the difference when we use labels.
1 1

If you observe, it is evident that we can only break the outer loop with the help of labels. This is one of the primary uses of labelled for loops in Java.

Quiz on Java For Loop

Summary

Summing up, looping is an integral part of programming and for loops are extremely useful as it allows us to repeatedly execute statements when we know how many times we want to repeat them.

We learned about for loops, its syntax, and enhanced for-loops along with examples.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *