Loops in Java is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true.

While all three types’ basic functionality remains the same, there’s a vast difference in the syntax and how they operate.

For loop in Java iterates over code based on a condition, commonly used for arrays or calculations. Mastering it is crucial for efficient iteration and data processing. Enroll in a Java Course to explore for loops and more programming constructs.

In this article, you will focus on for loop in Java. But before delving deep into for loop and how to use it, let’s understand the difference between the three types of loops.

The Difference Between For Loop - While Loop - Do-While Loop

There are several differences among the three types of loops in Java, such as the syntax, optimal time to use, condition checking, and so on. The table below represents some of the primary dissimilarities between all the loops in Java.

Difference

For Loop

While Loop

Do-While Loop

Introduction

For loop in Java iterates a given set of statements multiple times.

The Java while loop executes a set of instructions until a boolean condition is met.

The do-while loop executes a set of statements at least once, even if the condition is not met. After the first execution, it repeats the iteration until the boolean condition is met.

Best time to use

Use it when you know the exact number of times to execute the part of the program.

Use it when you don’t know how many times you want the iteration to repeat.

Use it when you don’t know how many times you want the iteration to repeat, but it should execute at least one time.

Syntax

for(init; condition; icr/dcr){

//statements to be repeated

}

while(condition){

//statements to be repeated

}

do{

//statements to be repeated

}while(condition);

Example

for(int x=0; x<=5; x++){

System.out.println(x);

}

int x=0;

while(x<=5){

System.out.println(x);

x++;

}

int x=0;

do{

System.out.println(x);

x++;

}while(x<=5);

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

For Loop in Java

As mentioned, Java for loop helps execute a set of code repeatedly, and it is recommended when the number of iterations is fixed. You have seen the syntax of for loop, now try to understand it.

Syntax:

for(init; condition, incr/decr){

//statements to be executed or body

}

In the above syntax:

  • init: The init expression is used for initializing a variable, and it is executed only once.
  • condition: It executes the condition statement for every iteration. If it evaluates the condition to be true, it executes the body of the loop. The loop will continue to run until the condition becomes false.
  • incr/decr: It is the increment or decrement statement applied to the variable to update the initial expression.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Thus, the Flow of for Loop in Java Is:

/flowofforloop

Let’s look at a simple for loop example to understand the syntax and how it operates.

public class forExample{

public static void main(String args[]) {

for(int x=0; x<=5; x++){

             System.out.println(x);   

         }

     }

}

Output:

ForLoop_1.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Types of For Loops in Java

There are three types of for loops in Java:

  • Simple
  • For-each or enhanced
  • Labeled

You will go through each type of Java for loops with examples.

Simple For Loop in Java

A simple for loop is what you have seen until now, including the flow and syntax. Here’s an example where you must print the values from 1 to 10.

Example of simple for loop:

public class forExample{

public static void main(String args[]) {

for(int x=1; x<=10; x++){

             System.out.println(x);   

         }

     }

}

Output:

TypeForLoop

For-each Loop in Java

The Java for-each loop is used on an array or a collection type. It works as an iterator and helps traverse through an array or collection elements, and returns them. While declaring a for-each loop, you don’t have to provide the increment or decrement statement as the loop will, by default, traverse through each element. Here’s the syntax:

for(Type var:array){  

//loop body

}

Example of for-each loop:

public class ForEach{  

    public static void main(String[] args){  

        //Array declaration  

        int ar[]={1,2,3,5,7,11,13,17,19};  

        //Using for-each loop to print the array  

        for(int x:ar){

            System.out.println(x);  

        }  

    }  

}

Output:

ForEachLoop

Labeled For Loop in Java

With the labeled for loop in Java, you can label the loops. It is useful when you have a nested loop (more about it later) and want to use the break or continue keyword for the outer loop instead of the inner one. Usually, the break and continue keyword works on the innermost loop by default. The syntax of Java labeled for loop is:

labelname:  

for(initialization;condition;incr/decr){  

//loop body

}

Example of labeled for loop

public class LabeledForLoop{  

    public static void main(String[] args){  

        //Using Labels 

        Label1:  

            for(int x=1;x<=5;x++){  

                Label2:  

                    for(int y=1;y<=4;y++){  

                        if(x==3&&y==2){  

                            break Label1;  

                        }  

                        System.out.println(x+" "+y);  

                    }  

            }  

    }  

}

Output:

LabeledForLoop

As you can see in the above example, this demo has used the label name to break the outer loop, which is the opposite of a loop’s default behavior.

Nested For Loop in Java

Java nested for loop is not a separate type of loop. It is just using one or multiple for loops inside another. Whenever the outer loop meets the condition, the inner loop is executed completely. It is usually used for pattern programs to print distinct patterns in the output. The example below uses the nested for loop in Java to print a pyramid.

public class NestedForExample{  

    public static void main(String[] args){  

        for(int x=1;x<=7;x++){

            for(int y=1;y<=x;y++){  

                System.out.print("* ");  

            }  

            //new line when the inner loop is executed completely

            System.out.println();

        }  

    }  

}

Output:

NestedForLoop

Become a Certified UI UX Expert in Just 5 Months!

UMass Amherst UI UX BootcampExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Infinite For Loop in Java

The Java infinite for loop is used if you want to keep running a certain set of code. Syntax of infinite for loop in Java is:

for(;;){

//loop body

}

Example of infinite for loop

public class InfiniteFor{  

    public static void main(String[] args) {  

        //Declaring the infinite for loop  

        for(;;){  

            System.out.println("Simplilearn");  

        }  

    }  

}

Output:

infiniteForLoop.

You can use ctrl + c to exit the infinite loop.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

In this for loop in Java article, you learned what loops are, and what are for loops in specific. You also looked at the types of loops, the difference between them, and the types of for loops with examples. 

If you want to learn about the other two types of loops: while and do-while, you can refer to Simplilearn’s Java Tutorial for Beginners: A Step-By-Step Guide. You can also opt for the Free Java Course for Beginners that includes around 9 hours of self-paced video lessons. But if you want to go a step further and excel in Java programming, go for our Online Java Certification Course. It offers you applied learning and hands-on experience with some of the most-popular Java environment frameworks, including Hibernate and Spring.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, soon!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449