0
0
Javaprogramming~5 mins

Difference between while and do–while in Java

Choose your learning style9 modes available
Introduction

We use loops to repeat actions. while and do-while loops help us repeat code, but they check the condition at different times.

When you want to repeat something only if a condition is true before starting.
When you want to run a block of code at least once, then repeat if a condition is true.
When you are reading user input and want to validate it before repeating.
When you want to keep asking for a password until it is correct, but show the prompt at least once.
Syntax
Java
while (condition) {
    // code to repeat
}

do {
    // code to repeat
} while (condition);

while checks the condition before running the code.

do-while runs the code once before checking the condition.

Examples
This prints numbers 0, 1, 2 because it checks before printing.
Java
int i = 0;
while (i < 3) {
    System.out.println(i);
    i++;
}
This also prints 0, 1, 2 but runs the print at least once even if condition is false.
Java
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 3);
This prints nothing because condition is false at start.
Java
int i = 5;
while (i < 3) {
    System.out.println(i);
    i++;
}
This prints 5 once because do runs before condition check.
Java
int i = 5;
do {
    System.out.println(i);
    i++;
} while (i < 3);
Sample Program

This program shows the difference: the while loop does not print because condition is false at start. The do-while loop prints once because it runs before checking.

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

        System.out.println("Using while loop:");
        while (count < 3) {
            System.out.println("Count is " + count);
            count++;
        }

        count = 5;
        System.out.println("Using do-while loop:");
        do {
            System.out.println("Count is " + count);
            count++;
        } while (count < 3);
    }
}
OutputSuccess
Important Notes

Use while when you want to check the condition first.

Use do-while when you want the code to run at least once.

Remember the semicolon ; after the do-while condition.

Summary

while checks condition before running code.

do-while runs code once before checking condition.

Choose based on whether you want the code to run at least once or not.