0
0
JavaHow-ToBeginner · 3 min read

How to Use While Loop in Java: Syntax and Examples

In Java, a while loop repeatedly executes a block of code as long as the given condition is true. The syntax is while (condition) { // code }, where the condition is checked before each iteration.
📐

Syntax

The while loop syntax in Java consists of the keyword while, followed by a condition in parentheses, and a block of code inside curly braces. The loop runs the code block repeatedly as long as the condition remains true.

  • while: keyword to start the loop
  • condition: a boolean expression checked before each loop iteration
  • code block: statements executed if the condition is true
java
while (condition) {
    // code to repeat
}
💻

Example

This example shows a while loop that counts from 1 to 5 and prints each number. The loop stops when the counter exceeds 5.

java
public class WhileLoopExample {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 5) {
            System.out.println("Count is: " + count);
            count++; // increase count by 1
        }
    }
}
Output
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
⚠️

Common Pitfalls

Common mistakes when using while loops include:

  • Forgetting to update the condition variable inside the loop, causing an infinite loop.
  • Using a condition that is always false, so the loop never runs.
  • Modifying the loop variable incorrectly, leading to unexpected behavior.

Always ensure the loop condition will eventually become false to stop the loop.

java
public class InfiniteLoopExample {
    public static void main(String[] args) {
        int i = 1;
        // Wrong: i is never updated, causes infinite loop
        while (i <= 5) {
            System.out.println(i);
            // missing i++ here
        }
    }
}

// Corrected version:
public class FixedLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++; // update to avoid infinite loop
        }
    }
}
📊

Quick Reference

  • Use while when you want to repeat code while a condition is true.
  • Check and update the condition variable inside the loop to avoid infinite loops.
  • The condition is tested before each iteration, so if false initially, the loop body won't run.

Key Takeaways

The while loop runs as long as its condition is true, checking before each iteration.
Always update variables inside the loop to eventually make the condition false and stop the loop.
If the condition is false at the start, the loop body will not execute even once.
Use while loops for repeating tasks when the number of repetitions is not known beforehand.