Java while Loop: A Comprehensive Tutorial with Code Examples

The while loop in Java is one of the most fundamental control flow statements. It repeatedly executes a block of code as long as a specified condition remains true.

This tutorial will walk you through the different ways to use the while loop with practical examples.

Table of Contents:

1. Introduction to while Loop

A while loop allows you to execute a block of code repeatedly based on a condition. As long as the condition evaluates to true, the code inside the loop is executed. If the condition becomes false, the loop terminates.

General Syntax:

while (condition) {
    // Code to be executed
}

condition: A boolean expression that is evaluated before each iteration.
If true: The loop executes the code block.
If false: The loop terminates.

2. Basic Syntax of while Loop

Example 1: Basic while Loop

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

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

Output:

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

In this example:

The while loop continues running as long as counter <= 5.
The counter is incremented by 1 during each iteration, and the loop terminates when counter exceeds 5.

3. Simple Example of while Loop

Example 2: Summing Numbers with while Loop

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

        while (number <= 10) {
            sum += number;  // Add the current number to sum
            number++;
        }

        System.out.println("The sum of numbers from 1 to 10 is: " + sum);
    }
}

Output:

The sum of numbers from 1 to 10 is: 55

In this example, the loop runs until number reaches 10, adding each number to the sum variable.

4. Infinite Loops with while

An infinite loop occurs when the condition in the while statement never becomes false. This results in the loop running indefinitely unless interrupted by an external factor or a break statement.

Example 3: Infinite Loop

public class Main {
    public static void main(String[] args) {
        while (true) {
            System.out.println("This is an infinite loop.");
            // You can add a break statement to stop the loop if necessary.
            // break;
        }
    }
}

In this example, the condition true is always true, so the loop will run forever unless you manually stop the program or use a break statement.

5. Using break and continue in while Loop

break: Terminates the loop immediately.
continue: Skips the current iteration and continues with the next iteration.

Example 4: Using break in a while Loop

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

        while (count <= 10) {
            if (count == 5) {
                break;  // Exit the loop when count is 5
            }
            System.out.println("Count: " + count);
            count++;
        }
    }
}

Output:

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

In this example, the loop is terminated using break when count equals 5.

Example 5: Using continue in a while Loop

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

        while (count < 10) {
            count++;

            if (count % 2 == 0) {
                continue;  // Skip the rest of the loop for even numbers
            }

            System.out.println("Odd number: " + count);
        }
    }
}

Output:

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

In this example, continue is used to skip even numbers and only print odd numbers.

6. while Loop vs do-while Loop

While a while loop checks the condition before executing the loop, the do-while loop checks the condition after the code block is executed. This means that a do-while loop will always execute at least once, even if the condition is false.

Syntax of do-while Loop:

do {
    // Code to be executed
} while (condition);

Example 6: do-while Loop

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

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

Output:

Count: 5

In this case, the loop executes once because the do block runs before the condition is checked, even though count starts at 5, which is greater than 3.

7. Nested while Loops

You can nest while loops within other while loops, allowing you to handle multi-level iterations (e.g., working with 2D arrays).

Example 7: Nested while Loops

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

        while (outer <= 3) {
            int inner = 1;

            while (inner <= 2) {
                System.out.println("Outer: " + outer + ", Inner: " + inner);
                inner++;
            }

            outer++;
        }
    }
}

Output:

Outer: 1, Inner: 1
Outer: 1, Inner: 2
Outer: 2, Inner: 1
Outer: 2, Inner: 2
Outer: 3, Inner: 1
Outer: 3, Inner: 2

In this example, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs twice.

8. Best Practices for Using while Loops

Avoid infinite loops: Ensure that your condition will eventually evaluate to false. Without this, your loop will run forever, consuming system resources.

Use break cautiously: break can be used to terminate a loop early, but overusing it can make the code harder to follow. Ensure the logic is clear.

Keep track of loop variables: Make sure you modify the loop control variable (like counter++) inside the loop to avoid infinite loops.

Consider readability: If your loop’s logic becomes complex, consider refactoring it into smaller methods to improve readability.

9. Common Use Cases for while Loops

Example 8: User Input Validation with while

import java.util.Scanner;

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

        do {
            System.out.println("Enter a number between 1 and 10:");
            number = scanner.nextInt();
        } while (number < 1 || number > 10);

        System.out.println("You entered: " + number);
    }
}

Output (Example input: 11, then 6):

Enter a number between 1 and 10:
11
Enter a number between 1 and 10:
6
You entered: 6

This example ensures that the user provides a valid input (between 1 and 10) before proceeding.

Example 9: Simulating a Countdown

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

        while (countdown > 0) {
            System.out.println("Countdown: " + countdown);
            countdown--;
        }

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

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!

This example simulates a simple countdown using a while loop.

Conclusion

The while loop is a powerful tool for repeating a block of code as long as a condition remains true.

Whether you're validating user input, summing numbers, or running complex logic, the while loop provides the flexibility needed to handle various use cases.

By understanding how to use break, continue, and nested loops, you can implement efficient and readable loops in your Java programs.

Related posts

Java break and continue Statements Tutorial

Java for-each Loop: A Comprehensive Tutorial with Code Examples

Java do-while Loop: A Comprehensive Tutorial with Code Examples