while and do-while Loops

Learn Java while and do-while loops with examples and explanations. Day 8 Java course tutorial for beginners.
while and do-while Loops

Java Loops: while and do-while

On Day 8, we explore loops. Loops let us repeat code without writing it multiple times. In Java, while and do-while loops are commonly used when the number of repetitions is not known in advance.

1. while Loop

The while loop runs as long as its condition is true. If the condition is false at the start, it will not execute at all.


public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}

How it works: The variable i starts at 1. The loop runs until i becomes 6. Each time, it prints the value of i and then increments it by 1.

2. do-while Loop

The do-while loop is similar to while, but it executes the block at least once, even if the condition is false.


public class DoWhileExample {
    public static void main(String[] args) {
        int i = 6;
        do {
            System.out.println("Count: " + i);
            i++;
        } while (i <= 5);
    }
}

How it works: Here, the condition i <= 5 is false from the start (since i = 6). But because do runs before checking the condition, the message prints once before stopping.

3. Difference Between while and do-while

  • while: checks condition first → may not run at all.
  • do-while: runs once, then checks condition → always executes at least once.

Summary

Loops are powerful for repetition. Use while when you want to test first, and do-while when you need the code to run at least once no matter what.

Post a Comment