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

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

13 Jan 2025
Beginner
29.3K Views
37 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Loops in Java

Loops in Java are powerful constructs that help you execute repetitive tasks efficiently. They allow a block of code to run multiple times based on a specific condition, making your code more concise and organized. By automating repetitive operations, loops help reduce errors and improve overall code readability.

In this Java Tutorial, we’ll break down the various types of loops in Java and explain how to use them effectively. Whether you’re solving basic problems or building complex systems, understanding loops is essential for efficient programming.

Boost your skills with our in-depth Java Full Stack Developer Certification Training. Enroll today and take your career to the next level!

What Are Loops in Java?

Loops in Java are a fundamental feature that allows you to execute a block of code repeatedly based on a condition. They are essential for automating repetitive tasks, reducing manual effort, and making your code more concise and efficient.

Why Use Loops?

Imagine performing the same operation multiple times manually. It’s tedious and error-prone, right? Loops solve this by automating repetitive tasks, ensuring accuracy and saving time.

    Benefits of Using Loops

    • Efficient code execution: Loops allow you to perform repetitive tasks without writing the same code multiple times, making your code cleaner and more efficient.
    • Improved readability: With loops, you can condense repetitive logic into a single structure, making your code easier to understand and maintain.
    • Flexibility: Loops offer flexibility in controlling the flow of your program by adjusting the iteration conditions, making them ideal for dynamic tasks.
    • Reduction in errors: By using loops, you avoid redundancy in your code, which minimizes the chance of introducing errors when repeating logic.
    • Time-saving: Loops help in automating repetitive tasks, saving time during development and reducing manual coding efforts.
    Read More: Java Interview Questions and Answers

    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 is ideal when you know exactly how many times you want to repeat a task or loop through a sequence of values.
    • It consists of three main components: initialization (setting up the starting point), condition (the condition that must be true for the loop to continue), and increment/decrement (how the loop variable changes after each iteration).
    • Use the for loop to easily iterate over arrays, collections, or a specific range of numbers, ensuring you don’t repeat code unnecessarily.
    • With a for loop, you can make your code more readable, compact, and maintainable, avoiding the need for repetitive lines of code.

    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 perfect for situations where you don’t know beforehand how many times the loop will run, but you have a condition that needs to be true for it to continue.
    • The loop continues executing as long as the condition is true, making it useful for situations like waiting for user input or continuously processing data until a certain condition is met.
    • With a while loop, you can perform repetitive tasks where the exact number of iterations isn't known, making your program more dynamic and flexible.
    • Want to keep things efficient? A while loop avoids unnecessary iterations by checking the condition before each execution, saving time and resources.

    While loops in Java

    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 is similar to the while loop, but with a key difference: it always runs at least once, even if the condition is false right from the start.
    • It's useful when you need to execute a block of code first and then check the condition afterward, ensuring the code runs at least once before making any decisions.
    • Do-whileloophelpsin scenarios like menu-driven applications, where you want to display the menu first and then check if the user wants to repeat the action.
    • Need guaranteed execution of the code block at least once? The Do-while loop is your go-to solution, making it perfect for tasks that must be executed even if the condition fails immediately.

    Do..while loops in Java

    Read More: Java Developer Salary

    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

    Infinite loops in Java occur when a loop continues endlessly because the termination condition is never met. You can create them intentionally using loops like while(true) or unintentionally due to logic errors. Handle them carefully to avoid program crashes. Let's see infinite loops with different loops:

    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

    An infinite while loop in Java happens when the condition in your while loop is always true. For example, using while(true) creates an endless loop. You can stop it with a break statement or by fixing the condition. Have you ever encountered 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

    An infinite do-while loop in Java happens when the condition in your do-while loop always evaluates to true. For example, do { } while(true); keeps running endlessly. You can stop it with a break statement or by adjusting the condition. Have you tried one before?

    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

    Nested loops in Java are loops inside another loop, where the inner loop runs completely for each iteration of the outer loop. They are useful for tasks like iterating through Single Dimensional and Multi-Dimensional Arrays or creating patterns.

    1. Nested for loop in Java

    A nested for loop in Java is a for loop inside another for loop. The inner loop runs completely for each iteration of the outer loop. It’s great for tasks like iterating over 2D arrays or generating patterns. Have you experimented with one?

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

    Output

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

    Explanation

    • 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.

    2. Nested While Loop in Java

    A nested while loop in Java is a while loop placed inside another while loop. The inner loop executes entirely for each iteration of the outer loop. It’s helpful for processing 2D data or creating complex patterns. Have you used it for such tasks?

    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++;
            }
        }
    }
    

    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
    

    Explanation

    • 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.

    3. Nested Do-While Loop in Java

    A nested do-while loop in Java is a do-while loop inside another do-while loop. The inner loop executes completely for each iteration of the outer loop. This structure is useful when you need to work with multi-dimensional data or generate specific patterns.

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

    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
    

    Explanation

    • 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.

    4. Nested while and for loop

    A nested while loop and for loop in Java involves placing a while loop inside a for loop or vice versa. For each iteration of the outer loop (either while or for), the inner loop will run completely. This combination is useful when you need to perform tasks like iterating through multi-dimensional data or complex calculations. Have you tried using this combination for any particular problem?

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

    Output

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

    Explanation

    • 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.

    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

    This article explored the different types of loops in Java, including for, while, and do-while loops. These loops are essential for iterating over data structures, executing repeated tasks, and simplifying complex operations. Understanding how loops work is key to mastering Java programming. Want to enhance your Java programming skills? Join the Scholarhat Java Programming Course and start building real-world projects today! Scholarhat Master Classes offer hands-on training in technologies like Microsoft Azure Administrator, ReactJS, and Python. Enhance your career and gain expertise with real-world projects. Join now!

    Exclusive Free Courses: Scholarhat offers some amazing free courses to help you enhance your skills. Here are Free Courses to Master Job-Ready Coding Skills for Your Dream Career!

    • Free Java Course - Master the essentials of Java programming with this comprehensive course.
    • Free Python Course - Learn Python programming from scratch and start building real-world applications.
    • Free C++ Course - Master C++ programming and build high-performance applications.
    Did You Know? Quiz

    Did You Know? Quiz

    Q1: "An infinite loop can occur in Java without specifying conditions."

    • True
    • False
    Answer: True

    Explanation: In Java, an infinite loop can occur if you do not provide a condition to terminate the loop, for example in a `while` loop with no condition specified.

    Q2: "A `do-while` loop will execute at least once, even if the condition is false."

    • True
    • False
    Answer: True

    Explanation: The `do-while` loop executes its body at least once before checking the condition.

    Q3: "The `for-each` loop can iterate over arrays and collections."

    • True
    • False
    Answer: True

    Explanation: The `for-each` loop in Java is used to iterate over arrays and collections like `ArrayList` and `HashSet`.

    Q4: "A `break` statement can be used to exit a loop prematurely."

    • True
    • False
    Answer: True

    Explanation: The `break` statement is used to terminate a loop or switch statement immediately.

    Q5: "The `continue` statement skips the current iteration of a loop."

    • True
    • False
    Answer: True

    Explanation: The `continue` statement skips the current iteration of a loop and jumps to the next iteration.

    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)

    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