Java While Loop (Simple Explanation + Live Examples)

βœ… What is a While Loop?

The while loop in Java is a control flow statement that allows you to repeatedly execute a block of code as long as a condition remains true. Unlike the for loop, the while loop is preferred when the number of iterations is not known beforehand β€” the loop continues running until the condition becomes false.


🧠 Syntax of the While Loop

while (condition) {
// Code to execute repeatedly
}
  • Condition: It must return true or false.

  • If the condition is true, the loop runs.

  • If it’s false, the loop exits.


🎯 Example 1: Print Numbers from 1 to 5

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

🎯 Example 2: Input Until User Enters 0

import java.util.Scanner;

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

System.out.println("Enter numbers (0 to stop):");
num = scanner.nextInt();

while (num != 0) {
System.out.println("You entered: " + num);
num = scanner.nextInt();
}

System.out.println("Loop ended.");
}
}

Output:

Enter numbers (0 to stop):
5
You entered: 5
8
You entered: 8
0
Loop ended.

⚠️ Infinite While Loop Example

while (true) {
System.out.println("This will run forever!");
}

This creates an infinite loop, which must be exited using a break statement or other logic. Use with caution.


πŸ“ Key Points

  • If the condition is false at the start, the loop does not run even once.

  • Ensure the loop modifies the condition inside the block, or it may run forever.

  • Best used when waiting for a condition to be met (e.g., user input, flag update, file reading).


βœ… When to Use a While Loop

  • You don’t know how many times the loop should run.

  • You want the loop to continue until something happens (like a user input).

  • You need pre-condition checking before entering the loop.

Related Posts