for Loop in Java: Its Types and Examples

for Loop in Java: Its Types and Examples

26 Dec 2024
Beginner
3.07K Views
11 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

for Loop in Java

The for loop in Java provides a functionality. It is nothing but a repetition control structure that allows us to efficiently write a loop that needs to be executed a specific number of times. It contains the initialization, condition, and updating statements as part of its syntax.

In the last Java Tutorial, you got a glimpse of Loops in Java and its different types. You got a short overview of Java for loop. In this tutorial, you will get to learn about the for loop in Java in detail. To explore more about different concepts of Java, consider enrolling in our Java Certification Course Free right now!

Read More: 

What is a for loop in Java?

Java for loop is a looping statement in Java. It allows the Java developers to repeat the execution of a block of code for a specified number of times.

Flowchart of for loop in Java

java for loop flowchart

Syntax of for loop in Java

The basic syntax of a Java for loop looks like this:
for (initialization; condition; update) {
    // code to be executed
}

Explanation:

There are three terms that you need to understand in the above syntax,
  • Initialization is used for initializing the variable of the loop.
  • Condition is used for the evaluation of the variable to check if it is 'True' and continues further. If it is evaluated to be 'False', the loop terminates.
  • Update is used for modifying the variable after each iteration is completed.

Example of for loop in Java in Java Compiler:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Explanation:

In the above example,
  • We have initialized the loop variable 'i' to'1'.
  • Then, we check if i is less than or equal to 5. If the condition is 'True', the loop will continue. If it turns out to be 'False', the loop will terminate.
  • With 'i++', there will be an increment of 1 in 'i' after each iteration.

Output

1
2
3
4
5

Read More: Java Developer Salary Guide in India

Types of for Loops in Java

There are majorly 5 different types of for loops in Java you can use in your Java Program. Let's try to understand their usage with Examples in Java Online Editor:

1. Simple for Loop in Java

The simple for loop in Java repeats the execution of block of code for a known and fixed number of times.

Example of simple for loop:

for (int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2. for-each Loop in Java

The for-each loop in Java is used on an array or a collection. It repeats execution for each element of that array or collection.

Example of for-each loop:

int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {
    System.out.println("Number: " + num);
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

3. Labeled for Loop in Java

A labeled for loop in Java is used when you want to label the loop. The labeling is done before the loop and 'break' and 'continue' statements can be used control the flow of nested loops.

Example of labeled for loop:

outerLoop:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break outerLoop;
        }
        System.out.println("i: " + i + ", j: " + j);
    }
}

Output

i: 1, j: 1
i: 1, j: 2

4. Nested for Loop in Java

A Nested for loop in Java is simply a for loop nested inside another for loop. It is mainly used for multi-level iterations.

Example of nested for loop:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println("i: " + i + ", j: " + j);
    }
}

Output

i: 1, j: 1
i: 1, j: 2
i: 2, j: 1
i: 2, j: 2
i: 3, j: 1
i: 3, j: 2

5. Infinite for Loop in Java

An infinite for loop in Java is a indefinitely running loop because the condition this for loop will always to 'True'. It runs until any kind of interruption is made to it.

Example of infinite for loop:

for (;;) {
    System.out.println("This is an infinite loop");
}

Output

This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop...

Difference Between for, while Loop and do...while Loop in Java

You just learned about Java for loop. Now, you might be wondering what makes it different from the other types of loops in Java. We will see that through the below comparison table:
Aspectfor Loopwhile Loopdo...while Loop
InitializationInitialization is done inside the loop.Initialization is done before entering the loop.Initialization is done before entering the loop.
Condition CheckCondition checking occurs at the beginning of each iteration.Condition is checked at the beginning of each iteration.It checks the condition at the end of each iteration.
ExecutionIt will execute the code block only if condition is 'True'.It will execute the code block only if condition is 'True'.It will execute the code block at least and then, check the condition.
UpdationThe loop variable is updated after each iteration.The loop variable is updated within or at the end of the loop.The loop variable is updated after each iteration.
Use CaseIt is suitable when the number of iteration is known in advance.It is suitable when the number of iterations is not predetermined.It is suitable when you want that the code block of the loop is executed at least once.
Summary
Through this article, you learnt about for loop in Java, different types of Java for loop and much more. If you are new to these concepts of Java, we recommend you to grab our comprehensive Java Online Course Free With Certificate which is an enhanced step by step guide to Java Programming from scratch to Expert..

FAQs

The syntax of for loop in Java looks like this:
for (initialization; condition; update) {
    // code to be executed
}

The basic syntax of a loop in Java is same for all loops with slight variations in each one.
for (initialization; condition; update) {
    // code to be executed
}

The syntax of while loop in Java is:
while (condition) {
    // code to be executed
}

The three types of loops in Java are as follows:
  1. for loop
  2. while loop
  3. do-while loop

A loop in Java is a control structure that is used for repeating a block of code multiple times based on certain specified conditions. Its types are: for, while and do-while.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this