For Loop in Java: Its Types and Examples

For Loop in Java: Its Types and Examples

16 Apr 2024
Beginner
120 Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

for Loop in Java: An Overview

for loop in Java is one of the basic concepts of Java that you should definitely know. In the last Java Tutorial, you got a glimpse of Loops in Java and its different types, where you got a short overview of Java for loops. In this tutorial, you will get to learn about What is for loop in Java?, Different Types of for loops in Java with examples and much more in detail. To explore more about different concepts of Java, consider enrolling in our Java Certification Training right now!

Read More: Top 50 Java Interview Questions and Answers

What is for loop in Java?

Java for loop is a looping statement in Java. It allows the Java developers to repeat 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 Certification Course 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 Training Batches Schedule
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 8th time in a row (2016-2023). 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.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this