Control Flow

Java While Loop

Learn about while and do-while loops in Java — syntax, use cases, and how they differ from for loops.

What is a While Loop?

A while loop repeats a block of code as long as a condition is true. Unlike a for loop, you use a while loop when the number of iterations is not known in advance.

java
while (condition) {
    // Code to execute
    // Must update condition to avoid infinite loop
}

Basic While Loop

java
public class WhileDemo {
    public static void main(String[] args) {
        int count = 1;

        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Do-While Loop

The do-while loop executes the code block at least once before checking the condition:

java
do {
    // Code executes at least once
} while (condition);
java
import java.util.Scanner;

public class MenuSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n=== Menu ===");
            System.out.println("1. Say Hello");
            System.out.println("2. Say Goodbye");
            System.out.println("3. Exit");
            System.out.print("Enter choice: ");
            choice = scanner.nextInt();

            switch (choice) {
                case 1 -> System.out.println("Hello!");
                case 2 -> System.out.println("Goodbye!");
                case 3 -> System.out.println("Exiting...");
                default -> System.out.println("Invalid choice!");
            }
        } while (choice != 3);

        scanner.close();
    }
}

While vs Do-While vs For

Featurewhiledo-whilefor
Condition checkBefore loop bodyAfter loop bodyBefore loop body
Min executions010
Best forUnknown iterationsMust run at least onceKnown iterations

Practical Example: Number Guessing Game

java
import java.util.Scanner;
import java.util.Random;

public class GuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        int secret = random.nextInt(100) + 1;
        int guess;
        int attempts = 0;

        System.out.println("I'm thinking of a number between 1 and 100.");

        do {
            System.out.print("Your guess: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess < secret) {
                System.out.println("Too low! Try again.");
            } else if (guess > secret) {
                System.out.println("Too high! Try again.");
            }
        } while (guess != secret);

        System.out.printf("Correct! You guessed it in %d attempts.%n", attempts);
        scanner.close();
    }
}

Infinite Loop with While

java
// Common pattern for servers, game loops
while (true) {
    // Process requests...
    if (shouldStop) break;
}

Summary

  • while loops repeat while a condition is true — condition checked before each iteration
  • do-while loops guarantee at least one execution — condition checked after
  • Use while when iterations are unknown; use for when iterations are known
  • Always ensure the loop condition eventually becomes false to avoid infinite loops
  • do-while is ideal for menu systems and input validation