How to write Java while Loop

The while loop in Java repeatedly executes a block of code as long as a specified condition is true. It’s useful when you don’t know in advance how many times the loop should run, but you know the condition that should be met to stop the loop.

1. Syntax of while Loop

while (condition) {
    // Code to be executed
}
  • The condition is a boolean expression that is evaluated before each iteration of the loop.
  • If the condition is true, the loop body (code inside the loop) is executed.
  • The loop continues to execute until the condition becomes false.

2. Example of a while Loop

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

        while (i < 5) {
            System.out.println(i);
            i++;  // Increment the value of i
        }
    }
}

Output:

0
1
2
3
4

In this example, the while loop runs as long as i is less than 5. On each iteration, the value of i is printed and then incremented by 1. When i reaches 5, the condition i < 5 becomes false, and the loop stops.

3. Infinite while Loop

A while loop can continue indefinitely if the condition never becomes false. This is known as an infinite loop and should be avoided unless intentionally required (e.g., in servers or long-running tasks).

Example:

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

        while (i >= 0) {
            System.out.println(i);
            i++;
        }
    }
}

In this case, because i is always increasing and the condition i >= 0 is always true, the loop will run infinitely, printing values of i forever.

4. Breaking Out of a while Loop

You can use the break statement to exit a while loop prematurely if certain conditions are met inside the loop.

Example:

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

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

Output:

0
1
2
3
4
5

In this example, when i reaches 5, the break statement is executed, and the loop terminates, even though the condition i < 10 is still true.

5. Skipping Iterations with continue

The continue statement can be used to skip the current iteration and move to the next one without completing the remaining code in the loop.

Example:

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

        while (i < 10) {
            i++;

            if (i == 5) {
                continue;  // Skip the rest of the loop when i is 5
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
6
7
8
9
10

Here, when i equals 5, the continue statement skips the System.out.println(i) line and moves to the next iteration.

6. while Loop vs. for Loop

The while loop is preferred when you don’t know the exact number of iterations in advance. If you know the number of iterations, a for loop is usually more appropriate and compact.

while Loop Example:

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

for Loop Equivalent:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

7. Nested while Loops

You can nest while loops inside one another. This is useful for working with multi-dimensional data like matrices or tables.

Example:

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

        while (i <= 3) {
            int j = 1;

            while (j <= 3) {
                System.out.println("i = " + i + ", j = " + j);
                j++;
            }

            i++;
        }
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In this example, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 3 times, resulting in 9 printed lines.

8. Summary

  • The while loop repeats a block of code as long as the condition is true.
  • Be cautious of infinite loops if the condition never becomes false.
  • The break statement can be used to exit the loop prematurely.
  • The continue statement can be used to skip to the next iteration.
  • Nested while loops can be used to work with multi-dimensional data or nested tasks.

The while loop provides flexibility when the number of iterations is unknown or dynamic, making it a powerful tool for controlling the flow of your program based on conditions.

How to write Java while Loop

The while loop in Java repeatedly executes a block of code as long as a specified condition is true. It’s useful when you don’t know in advance how many times the loop should run, but you know the condition that should be met to stop the loop.

1. Syntax of while Loop

while (condition) {
    // Code to be executed
}
  • The condition is a boolean expression that is evaluated before each iteration of the loop.
  • If the condition is true, the loop body (code inside the loop) is executed.
  • The loop continues to execute until the condition becomes false.

2. Example of a while Loop

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

        while (i < 5) {
            System.out.println(i);
            i++;  // Increment the value of i
        }
    }
}

Output:

0
1
2
3
4

In this example, the while loop runs as long as i is less than 5. On each iteration, the value of i is printed and then incremented by 1. When i reaches 5, the condition i < 5 becomes false, and the loop stops.

3. Infinite while Loop

A while loop can continue indefinitely if the condition never becomes false. This is known as an infinite loop and should be avoided unless intentionally required (e.g., in servers or long-running tasks).

Example:

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

        while (i >= 0) {
            System.out.println(i);
            i++;
        }
    }
}

In this case, because i is always increasing and the condition i >= 0 is always true, the loop will run infinitely, printing values of i forever.

4. Breaking Out of a while Loop

You can use the break statement to exit a while loop prematurely if certain conditions are met inside the loop.

Example:

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

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

Output:

0
1
2
3
4
5

In this example, when i reaches 5, the break statement is executed, and the loop terminates, even though the condition i < 10 is still true.

5. Skipping Iterations with continue

The continue statement can be used to skip the current iteration and move to the next one without completing the remaining code in the loop.

Example:

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

        while (i < 10) {
            i++;

            if (i == 5) {
                continue;  // Skip the rest of the loop when i is 5
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
6
7
8
9
10

Here, when i equals 5, the continue statement skips the System.out.println(i) line and moves to the next iteration.

6. while Loop vs. for Loop

The while loop is preferred when you don’t know the exact number of iterations in advance. If you know the number of iterations, a for loop is usually more appropriate and compact.

while Loop Example:

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

for Loop Equivalent:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

7. Nested while Loops

You can nest while loops inside one another. This is useful for working with multi-dimensional data like matrices or tables.

Example:

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

        while (i <= 3) {
            int j = 1;

            while (j <= 3) {
                System.out.println("i = " + i + ", j = " + j);
                j++;
            }

            i++;
        }
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In this example, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 3 times, resulting in 9 printed lines.

8. Summary

  • The while loop repeats a block of code as long as the condition is true.
  • Be cautious of infinite loops if the condition never becomes false.
  • The break statement can be used to exit the loop prematurely.
  • The continue statement can be used to skip to the next iteration.
  • Nested while loops can be used to work with multi-dimensional data or nested tasks.

The while loop provides flexibility when the number of iterations is unknown or dynamic, making it a powerful tool for controlling the flow of your program based on conditions.