Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
for Loop in Java: Its Types and Examples

for Loop in Java: Its Types and Examples

06 Sep 2024
Beginner
1.73K Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

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 Full Stack Developer Course 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 Full Stack Developer Certification which is an enhanced step by step guide to Java Programming from scratch to Expert..

FAQs

Q1. What is for loop syntax in Java?

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

Q2. What is the syntax of a loop?

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
}

Q3. What is the syntax of while loop in Java?

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

Q4. What are the 3 types of loops in Java?

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

Q5. What is loop and its types?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Advanced Full-Stack .NET Developer Certification TrainingOct 05SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 05SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification TrainingOct 06SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Full-Stack .NET Developer Certification TrainingOct 06SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this