Understanding For Loop In Java With Examples

Loops in Java is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true. The Java programming language provides three types of loops:

  • For loop
  • While loop
  • Do-while loop

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

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);

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

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.

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.

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

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

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!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.