Java while Loop

In Java, the while loop is one of the fundamental looping constructs that allows you to execute a block of code repeatedly as long as a specified condition is true. It is especially useful when the number of iterations is not known in advance — that is, when you want to keep looping until a certain condition changes.

Syntax of the while Loop

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

Explanation:

  • The condition is a boolean expression that is evaluated before each iteration.
  • If the condition is true, the loop body executes.
  • When the condition becomes false, the loop stops, and control moves to the next statement after the loop.

Flow of Execution

  • The condition is evaluated.
  • If it’s true, the loop body executes.
  • After the loop body finishes, the condition is checked again.
  • This process repeats until the condition becomes false.
  • When the condition is false, the loop terminates.

In other words, the while loop is a “entry-controlled loop” because the condition is checked before the body executes.

Example 1: Basic while Loop

Let’s start with a simple program that prints numbers from 1 to 5 using a while loop.

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

    while (i <= 5) {
      System.out.println(“Number: ” + i);
      i++;
    }
  }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

  • The variable i starts with 1.
  • The loop runs as long as i <= 5.
  • After each iteration, i is incremented by 1.
  • When i becomes 6, the condition fails, and the loop stops.

Example 2: Sum of Natural Numbers

Here’s another example that calculates the sum of the first 10 natural numbers.

public class SumWhileExample {
  public static void main(String[] args) {
    int i = 1, sum = 0;

    while (i <= 10) {
      sum += i;
      i++;
    }

    System.out.println(“Sum of first 10 natural numbers: ” + sum);
  }
}

Output:

Sum of first 10 natural numbers: 55

Explanation:

Each iteration adds the current value of i to sum.
The loop stops once i becomes greater than 10.

Example 3: Using while Loop with User Input

You can also use a while loop to repeatedly accept user input until a specific condition is met.

import java.util.Scanner;

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

    while (number >= 0) {
      System.out.print(“Enter a number (negative to exit): “);
      number = sc.nextInt();
      if (number >= 0)
        System.out.println(“You entered: ” + number);
    }

    System.out.println(“Loop terminated because you entered a negative number.”);
    sc.close();
  }
}

Output (Example Run):

Enter a number (negative to exit): 10
You entered: 10
Enter a number (negative to exit): 25
You entered: 25
Enter a number (negative to exit): -5
Loop terminated because you entered a negative number.

Explanation:

The loop continues to run as long as the user enters a non-negative number.

When a negative number is entered, the condition becomes false and the loop stops.

Example 4: Infinite while Loop

Be careful — if the condition never becomes false, the loop will run forever, creating an infinite loop.

public class InfiniteWhileLoop {
  public static void main(String[] args) {
    while (true) {
      System.out.println(“This will run forever!”);
    }
  }
}

Explanation:

Since the condition true never changes, this loop will continue indefinitely unless you manually stop the program (e.g., with Ctrl + C).

Difference Between for and while Loops

Featurefor Loopwhile Loop
Use caseWhen the number of iterations is known.When the number of iterations is unknown.
Initialization, condition, incrementAll are in one line.Spread across multiple statements.
Entry checkChecks condition before loop body.Checks condition before loop body.
Syntax structureCompact.Flexible.
Examplefor (int i = 0; i < 5; i++)while (i < 5)

Example 5: Nested while Loops

You can also nest one while loop inside another to create patterns or handle multi-level iterations.

public class NestedWhileExample {
  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

Explanation:

The outer loop runs 3 times for i = 1 to 3.

For each iteration of the outer loop, the inner loop runs 3 times.

Key Points to Remember

  • Condition check first: The while loop checks the condition before executing the body.
  • May never run: If the condition is false initially, the loop body won’t execute even once.
  • Use when uncertain iterations: Best for loops where the number of repetitions isn’t fixed.
  • Watch for infinite loops: Always ensure the condition will eventually become false.

Conclusion

The Java while loop is a versatile construct that helps you execute repetitive tasks efficiently when you don’t know the exact number of iterations in advance. Its flexibility makes it ideal for tasks such as reading user input, waiting for conditions to change, or continuously monitoring a process — but always ensure your condition will eventually turn false to avoid infinite loops.

Scroll to Top