0
0
Javaprogramming~5 mins

Do–while loop in Java

Choose your learning style9 modes available
Introduction

A do-while loop lets you run a block of code at least once, then repeat it while a condition is true.

When you want to ask a user for input and repeat until they give a valid answer.
When you need to run a task first, then check if it should run again.
When you want to show a menu and repeat it until the user chooses to exit.
Syntax
Java
do {
    // code to run
} while (condition);

The code inside do { } runs first, before the condition is checked.

The loop repeats only if the condition after while is true.

Examples
This prints numbers 1 to 3, increasing count each time.
Java
int count = 1;
do {
    System.out.println("Count is " + count);
    count++;
} while (count <= 3);
This prints numbers 10, 9, and 8, then stops.
Java
int number = 10;
do {
    System.out.println("Number: " + number);
    number--;
} while (number > 7);
Sample Program

This program prints "Hello 1", "Hello 2", and "Hello 3" using a do-while loop.

Java
public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Hello " + i);
            i++;
        } while (i <= 3);
    }
}
OutputSuccess
Important Notes

The do-while loop always runs the code block at least once, even if the condition is false at the start.

Remember to update variables inside the loop to avoid infinite loops.

Summary

Do-while loops run code first, then check the condition.

They are useful when the code must run at least once.

Always ensure the loop condition will eventually become false.