Paramclasses Academy - Blog

Tutorials Details

What is Java Loops : For, While and Do-While with Examples ?

What is Java Loops : For, While and Do-While with Examples ?

October 21, 2026

Introduction

Loops are one of the most important concepts in Java programming. They allow developers to execute a block of code repeatedly while a condition is true or for a specified number of iterations.

Imagine you want to print the numbers from 1 to 100. Writing 100 separate print statements would be time-consuming and difficult to maintain. Instead, you can use a loop to perform the task with just a few lines of code.

Java provides three basic looping statements:

  • for loop

  • while loop

  • do-while loop

In this tutorial, you will learn how these loops work, when to use each one, and how to write practical Java programs using them.

What Is a Loop in Java?

A loop in Java is a control-flow statement that repeatedly executes a block of code based on a condition.

For example, the following program prints a message three times using a loop.

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Hello Java!");
        }
    }
}

Output:

Hello Java!
Hello Java!
Hello Java!

Instead of writing the same statement three times, the loop executes it automatically.

1. For Loop in Java

A for loop is useful when you know how many times you want to execute a block of code.

Syntax of the for Loop

for (initialization; condition; update) {
    // Code to execute
}

The three parts have different purposes:

  • Initialization: Sets the starting value of the loop variable.

  • Condition: Determines whether the loop should continue.

  • Update: Changes the loop variable after each iteration.

Example: Print Numbers from 1 to 5

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
5

How Does This Loop Work?

  1. int i = 1 initializes the variable.

  2. i <= 5 checks whether the condition is true.

  3. System.out.println(i) prints the current value.

  4. i++ increases the value by one.

  5. The condition is checked again until it becomes false.

When i becomes 6, the condition i <= 5 is false, so the loop stops.

Example: Print Even Numbers

public class Main {
    public static void main(String[] args) {
        for (int i = 2; i <= 10; i += 2) {
            System.out.println(i);
        }
    }
}

Output:

2
4
6
8
10

Here, i += 2 increases the value by two during every iteration.

Example: Calculate the Sum of Numbers from 1 to 5

public class Main {
    public static void main(String[] args) {
        int sum = 0;

        for (int i = 1; i <= 5; i++) {
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 15

The loop adds 1, 2, 3, 4, and 5 to the sum variable.

2. While Loop in Java

A while loop repeatedly executes a block of code as long as its condition remains true.

It is useful when you do not know in advance exactly how many iterations will be needed.

Syntax of the while Loop

while (condition) {
    // Code to execute
}

The condition is checked before the loop body executes. Therefore, if the condition is false at the beginning, the loop body will not run.

Example: Print Numbers from 1 to 5

public class Main {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

Output:

1
2
3
4
5

How Does This Loop Work?

  1. The variable i starts at 1.

  2. Java checks whether i <= 5.

  3. If true, the current value is printed.

  4. i++ increases the value.

  5. The condition is checked again.

When i becomes 6, the condition becomes false and the loop ends.

Important: Always ensure that the loop's condition can eventually become false when you want the loop to terminate. Forgetting to update the variable can create an infinite loop.

Example: Countdown Using a while Loop

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

        while (count >= 1) {
            System.out.println(count);
            count--;
        }

        System.out.println("Start!");
    }
}

Output:

5
4
3
2
1
Start!

This example demonstrates how a while loop can count down instead of counting up.

3. Do-While Loop in Java

A do-while loop is similar to a while loop, but it checks the condition after executing the loop body.

This means the code inside a do-while loop executes at least once, even if the condition is initially false.

Syntax of the do-while Loop

do {
    // Code to execute
} while (condition);

Notice the semicolon (;) after the while condition. It is required.

Example: Print Numbers from 1 to 5

public class Main {
    public static void main(String[] args) {
        int i = 1;

        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}

Output:

1
2
3
4
5

Special Example: Condition Is False

public class Main {
    public static void main(String[] args) {
        int i = 10;

        do {
            System.out.println("The loop executed!");
        } while (i < 5);
    }
}

Output:

The loop executed!

Why does this happen? Java executes the do block first. Only afterward does it check i < 5. Since the condition is false, the loop stops after its first execution.

This is the key difference between while and do-while.

Difference Between for, while and do-while Loops

Feature for Loop while Loop do-while Loop
Condition checked Before execution Before execution After execution
Minimum executions 0 0 1
Best suited for Known iteration counts Condition-based repetition At-least-once execution
Initialization Usually in loop header Usually before loop Usually before loop
Update Usually in loop header Usually in loop body Usually in loop body

Easy way to remember:

  • Use for when the number of repetitions is known.

  • Use while when repetition depends on a condition.

  • Use do-while when the code must execute at least once.

These are common guidelines, not strict restrictions. All three loops can solve many of the same problems.

4. Nested Loops in Java

A nested loop is a loop placed inside another loop.

Nested loops are commonly used for patterns, tables, matrices, and working with two-dimensional arrays.

Example: Print a Star Pattern

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print("* ");
            }

            System.out.println();
        }
    }
}

Output:

* * *
* * *
* * *

How Does It Work?

  • The outer loop controls the rows.

  • The inner loop controls the stars printed in each row.

  • System.out.print() prints on the same line.

  • System.out.println() moves to the next line after each row.

The inner loop completes all its iterations for every single iteration of the outer loop.

5. Enhanced for Loop in Java

Java also provides an enhanced for loop, commonly called the for-each loop. It is useful when you want to process each element of an array or a collection without managing an index manually.

Example: Print Array Elements

public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

10
20
30
40

Here, number receives each array element in sequence.

The enhanced for loop is convenient when you need to read or process every element. If you need an element's index or need to replace array elements by index, a traditional indexed loop may be more appropriate.

6. Break Statement in Java

The break statement immediately terminates the nearest enclosing loop. Program execution then continues with the statement after that loop.

Example

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
3
4

When i becomes 5, the break statement terminates the loop. The number 5 is not printed because break executes before the print statement.

7. Continue Statement in Java

The continue statement skips the remaining statements in the current iteration and moves to the next iteration of the loop.

Example: Skip Number 3

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
4
5

When i equals 3, the print statement is skipped for that iteration.

Remember: break exits the loop; continue skips only the current iteration.

8. Infinite Loops in Java

An infinite loop is a loop that continues indefinitely because its termination condition never becomes false, unless the loop is interrupted externally or by a statement such as break.

Example

public class Main {
    public static void main(String[] args) {
        while (true) {
            System.out.println("Running...");
        }
    }
}

This loop continues printing Running... until it is interrupted.

Infinite loops can be intentional in some programs, such as event-processing systems, but accidental infinite loops can make an application unresponsive.

How to Avoid Accidental Infinite Loops

  • Check whether the loop condition can become false.

  • Update the relevant variable correctly.

  • Ensure that the loop moves toward its termination condition.

  • Test the loop with small input values first.

9. Common Mistakes in Java Loops

Beginners often make these mistakes while writing loops.

Mistake 1: Using the Wrong Condition

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

This prints 1 through 4, not 1 through 5. Use i <= 5 if you want to include 5.

Mistake 2: Forgetting to Update the Variable

int i = 1;

while (i <= 5) {
    System.out.println(i);
}

The variable never changes, so the condition stays true. Add i++ inside the loop to make it progress toward termination.

Mistake 3: Adding an Extra Semicolon

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

The semicolon creates an empty loop body. The block that follows is separate and executes only once. Avoid placing an unnecessary semicolon immediately after the loop header.

Mistake 4: Forgetting the do-while Semicolon

Incorrect:

do {
    System.out.println("Hello");
} while (false)

Correct:

do {
    System.out.println("Hello");
} while (false);

The do-while statement requires a semicolon after its condition.

Frequently Asked Questions (FAQs)

1. What is a loop in Java?

A loop is a control-flow statement that repeatedly executes a block of code while a condition is satisfied or according to a specified iteration pattern.

2. What are the three main types of loops in Java?

The three basic looping statements are for, while, and do-while. Java also provides an enhanced for-each loop for processing arrays and collections.

3. What is the difference between while and do-while?

A while loop checks its condition before executing the body, so it may execute zero times. A do-while loop checks the condition afterward, so its body executes at least once.

4. When should I use a for loop?

Use a for loop when the repetition pattern is clear, such as printing numbers from 1 to 10 or iterating through a known range.

5. What is a nested loop?

A nested loop is a loop inside another loop. It is useful for creating patterns, processing matrices, and working with rows and columns.

6. What is the difference between break and continue?

break terminates the nearest enclosing loop. continue skips the remaining code in the current iteration and proceeds to the next iteration.

7. Can a for loop run without a condition?

Yes. For example, for (;;) { } creates an infinite loop unless it is terminated by another mechanism, such as break.

8. Which loop executes at least once?

The do-while loop always executes its body at least once because the condition is checked after the body.

Practice Exercises for Beginners

Try solving these exercises yourself to improve your Java programming skills.

  1. Write a program to print numbers from 1 to 20 using a for loop.

  2. Write a program to print all even numbers from 1 to 50.

  3. Write a program to calculate the sum of numbers from 1 to 100.

  4. Write a program to print the multiplication table of a number.

  5. Write a program to print numbers from 10 to 1 using a while loop.

  6. Write a program that demonstrates how a do-while loop executes when its condition is initially false.

  7. Create a right-angled triangle star pattern using nested loops.

  8. Write a program that skips all odd numbers using the continue statement.

Conclusion

Java loops help programmers repeat tasks efficiently and reduce unnecessary code. The for loop is useful for controlled repetition, the while loop is suitable for condition-based repetition, and the do-while loop is ideal when the body must execute at least once.

You should also understand nested loops, enhanced for loops, break, and continue to write better Java programs.

Practise these examples, experiment with different conditions, and make sure you understand how each iteration works before moving to the next topic.

Next Tutorial: Module 9 — Java Arrays Tutorial: One-Dimensional and Multidimensional Arrays.

Official References