Looping Statements in Java - For, While, Do-While Loop in Java

Looping Statements in Java - For, While, Do-While Loop in Java

11 Sep 2024
Beginner
27.9K Views
27 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Loops in Java: An Overview

Looping is one of the key concepts behind programming, and learning how to use loops in Java can open up a new world of code. Gain the foundational skills from this Java tutorial and move to the advanced Java training that includes in-depth coverage of loops and other essential programming concepts.

Become a full stack expert with our Java Full Stack Developer Certification Training—enroll and build your future!

What are loops in Java?

Loops are a block of code that executes itself until the specified condition becomes false. In this section, we will look in detail at the types of loops used in Java programming.

Read More - Advanced Java Interview Questions

Types of Loops in Java

There are three types of "Loops" in Java.

  1. for loop
  2. while loop
  3. do while loop

1. For loop in Java

  • For loop primarily depends on the three major sections index of the control statement which are the "declaration", "conditions" and "update" statements.
  • This particular loop statement generates iteration over a "collection of values". That can be the same value or can be different.
  • For loop is generally used when the user knows the exact number of iterations.
  • There are various types of "For loop" which are "Empty For Loop", "Infinite For Loop", and "For each loop".

For loop in Java

For loop flowchart explanation

  • Initialization condition: Here, the variable in use is initialized. It is the beginning of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
  • Test Condition: It is used for testing the exit condition for a loop. It must return a boolean value. For loop is an entry-controlled loop as the condition is checked before the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.
  • Update Statement: It is used for updating or incrementing/decrementing the variable for the next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of the for loop.

Java For loop Syntax

for (initialization; termination condition; increment/decrement)
{
//Set of statements to be executed repeatedly
}

Example For loop in Java in Java Compiler

//Program to print even numbers between 1-10.

class ForLoopDemo
{
public static void main(String[] args)
  {
   for (int i=1; i<=10; i++)
    {
     if (i%2==0)
     System.out.println(i);
    }
     System.out.println("Loop Ending");

  }
}

Output

2
4
6
8
10
Loop Ending 

2. While loop in Java

  • While Loop is also an iteration statement that can iterate over various types of values.
  • After accepting the condition While loop evaluates it to a "boolean value".
  • Execute a particular statement or a block of the statement until it generates "false".
  • While loop is used when the user is not aware of the exact iteration number.
  • There are various types of while loops; those are "Empty While Loop", and "Infinite While Loops".

While loops in Java

Read More - Java Developer Salary

While loop flowchart explanation

  • Test Condition: It is used for testing the exit condition for a loop. It must return a boolean value. While loop is an entry-controlled loop as the condition is checked before the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of the while loop.

Java While loop Syntax

//initialization
while (condition)
{
//Execute a set of statements
//increment
}

Example While loops in Java

class While_Loop_Demo
{
  //print even numbers ranging from 1 to 10

  public static void main(String args[])
 {
  int i = 1; //initialization
   while (i<=10) //condition or termination
   {

    if (i%2==0)
     {
       System.out.println(i);
     }

    i++; //increment
   }

 }
}

Output:

2
4
6
8
10

3. Do..while loops in Java

  • Do while loop works the same as while loop but it only generates the expression only after the execution of the code block has been done. The concept of Abstraction in Java can be applied to understand the Do-While loop better
  • This statement first executes the statement under "do" after that it checks the condition of "while".
  • This statement executes at least once even though the statement generates a "false" value.
  • Do while loop is an "exit control loop".
  • There is only one type of “Do while loop” which is called "Infinite Do While Loop".

Do..while loops in Java

Do...While loop flowchart explanation

  • Statement execution: The loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
  • Test Condition: After the statements execution step, the condition is checked for true or false value. If it is evaluated to be true, the next iteration of the loop starts.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of the do...while loop.

Java Do-While loop Syntax

do
{
//statements to be iterated
}
while(conditions);

Example Do..while loops in Java in the Java Online Editor

class Do_While_Loop_Demo
{
  //print even number
  public static void main(String args[])
 {

  int i = 1; //initialization
  do
   {
    System.out.println(i);

    i++; //increment
   } while (i%2==0);//condition or termination

 }
}

Output

1
2

Infinite loops in Java

1. Infinite for loop in Java

An infinite for loop gets created if the for loop condition remains true, or if the programmer forgets to apply the test condition/terminating statement within the for loop statement.

Syntax of Infinite for loop in Java


for(; ;) 
{ 
 // body of the for loop. 
} 

In the above syntax, there is no condition hence, this loop will execute infinite times.

Example of Infinite for loop in Java


public class Main {
    public static void main(String[] args) {
        for (;;) {
            System.out.println("Hello World");
        }
    }
}

In the above code, we have run the for loop infinite times, so "Hello World" will be displayed infinitely.

Output

Hello World
Hello World
Hello World
Hello World
Hello World
... 

2. Infinite while loop in Java

If the condition of a loop is always true, the loop becomes an infinite one.

Syntax of Infinite While loop in Java


while(true) 
{ 
 // body of the loop.. 
}

Example of Infinite While loop in Java


public class Main {
    public static void main(String[] args) {
        String str = "Infinite while loop";
        int i = 0;

        while (true) {
            i++;
            System.out.println("i is: " + i);
        }

        // The return statement may never be reached in an infinite loop.
        // return 0; // In Java, return 0 is not applicable for the main method.
    }
}

Here, the value of i will be printed n number of times due to the absence of a terminating condition.

Output

i is: 1
i is: 2
i is: 3
i is: 4
i is: 5
...

3. Infinite do...while loop in Java

It gets created when the testCondition remains true.

Syntax of Infinite While loop in Java


do 
{ 
 // body of the loop 
}while(true);

Example of Infinite do...While loop in Java


public class Main {
    public static void main(String[] args) {
        do {
            System.out.println("This is an infinite do-while loop.");
        } while (true);

        // The return statement may never be reached in an infinite loop.
        // return 0; // In Java, return 0 is not applicable for the main method.
    }
}

Output

This is an infinite do-while loop.
This is an infinite do-while loop.
This is an infinite do-while loop. 
...

Nested Loops in Java

1. Nested for loop in Java

It is any type of loop inside a for loop.

Nested for loop in Java

Example of Nested for loop in Java


public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
  • This Java code generates a pattern of numbers using nested loops.
  • The inner loop j iterates from 1 to the current value of i, printing numbers and spaces
  • The outer loop i iterates from 1 to 5, regulating the number of rows.
  • As a result, there is a pattern of numerals rising in each row, with a new line between each row.

Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

2. Nested While Loop in Java

It is any type of loop inside a whileloop.

Nested While Loop in Java

Example of Nested while loop in Java in Java Playground


public class Main {
    public static void main(String[] args) {
        int i = 1, j = 1;
        while (i <= 3) {
            System.out.println("Outer loop iteration " + i);
            while (j <= 3) {
                System.out.println(" Inner loop iteration " + j);
                j++;
            }
            j = 1; // reset j to 1 for the next iteration of the outer loop
            i++;
        }
    }
}
  • The inner loop j iterates within each iteration of the outer loop i, printing "Inner loop iteration" messages
  • The outer loop i iterates three times, printing "Outer loop iteration" messages.
  • After each inner loop is finished, j is reset to 1, resulting in nested iteration.

Output

Outer loop iteration 1
 Inner loop iteration 1
 Inner loop iteration 2
 Inner loop iteration 3
Outer loop iteration 2
 Inner loop iteration 1
 Inner loop iteration 2
 Inner loop iteration 3
Outer loop iteration 3
 Inner loop iteration 1
 Inner loop iteration 2
 Inner loop iteration 3

3. Nested Do...While Loop in Java

It is a do...while loop inside any do...while loop.

Nested Do...While Loop in Java

Example of Nested do...while loop in Java


public class Main {
    public static void main(String[] args) {
        int i = 1;
        do {
            int j = 1;
            do {
                System.out.println(i + " * " + j + " = " + (i * j));
                j++;
            } while (j <= 10);
            i++;
        } while (i <= 2);
    }
}
  • The above code creates and outputs multiplication tables of 1 and 2 from 1 to 10 using a nested loop structure.
  • It iterates over the values of i (1 and 2) and j (1 to 10), outputting the result of i * j after each iteration using two nested do...while loops.

Output

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

4. Nested while and for loop

Example of Nested while and for loop in Java in Java Online Compiler


public class NestedLoopsExample {
    public static void main(String[] args) {
        int rows = 5;

        // Nested for loop
        for (int i = 1; i <= rows; i++) {
            // Print spaces
            for (int j = 1; j <= rows - i; j++) {
                System.out.print("  ");
            }

            int num = 1;
            int col = 1;

            // Nested while loop
            while (col <= i) {
                System.out.print(num + " ");
                num++;
                col++;
            }

            System.out.println();
        }
    }
}

This Java program generates a triangle pattern with numbers increasing sequentially from 1 to the row number. The outer loop is a for loop, while the inner loop is a while loop, demonstrating the use of nested loops in Java.

Output

        1 
      1 2 
    1 2 3 
  1 2 3 4 
1 2 3 4 5 

Java for Loop vs while Loop vs do...while Loop

Parametersfor loopwhile loopdo-while loop
DefinitionThe Java for loop is a control flow statement that iterates a part of the program multiple times.The Java while loop is a control flow statement that executes a part of the programs repeatedly based on a given boolean condition.The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to useIf the number of iterations is fixed, it is recommended to use for loop.If the number of iterations is not fixed, it is recommended to use a while loop.If the number of iterations is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntaxfor(init;condition;incr/decr){ // code to be executed }while(condition){ //code to be executed }do{ //code to be executed }while(condition);
Summary

In this comprehensive Java tutorial article, Looping statements in Java can be used in a variety of ways to optimize code performance, meaning that implementation is dependent on individual program needs. Now that you've brushed up on your knowledge of both while and do-while loop concepts, it's time to get out there and start experimenting with different techniques for yourself!

Java Loops open a world of possibilities for you as a coder, especially if you're undergoing Full Stack Java Course, and offer countless opportunities for creativity. So, what will you create first as you dive into the exciting realm of Java loops during your Java Certification training?

FAQs

Looping statements in Java are constructs that allow you to repeatedly execute a block of code. They help in automating repetitive tasks by iterating through a set of instructions as long as a certain condition is met.


Java supports three types of looping statements:

  • for loop
  • while loop
  • do-while loop

The while loop is used when the number of iterations is not known beforehand and is based on a specified condition.

The do-while loop is similar to the while loop, but it ensures that the block of code is executed at least once, even if the condition is false.

Yes, you can nest loops in Java. This means placing one loop inside the body of another loop. It is often used for more complex iteration scenarios.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

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