While Loop in Java | Control Flow in Java

The while loop in Java is a control flow statement that allows code to be executed repeatedly based on a boolean condition. It's useful for scenarios where the number of iterations is not known beforehand.

Key Points on While Loop:

Syntax of While Loop:

Syntax Example

while (condition) {
    // Code to execute in each iteration
}

Example of While Loop in Java:

This example demonstrates a basic while loop that prints numbers from 1 to 5.

Code Example 1

public class PrintNumbersWhile {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++; // Increment the loop variable
        }
    }
}

Output for Code Example 1:

1
2
3
4
5

Using Control Statements:

This example shows how to use the break statement in a while loop.

Code Example 2

public class BreakWhileExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            if (i == 5) {
                break; // Exit the loop when i equals 5
            }
            System.out.println(i);
            i++;
        }
    }
}

Output for Code Example 2:

1
2
3
4

Example of a While Loop with Condition Change:

This example uses a while loop to sum numbers until a certain limit is reached.

Code Example 3

public class SumWhileExample {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1;
        while (i <= 5) {
            sum += i; // Add i to sum
            i++; // Increment i
        }
        System.out.println("Sum: " + sum);
    }
}

Output for Code Example 3:

Sum: 15

Detailed Explanation:

By mastering the while loop, developers can effectively manage the flow of their Java programs, especially in situations where the number of iterations is not predetermined.