While Loop
While Loop
A school program needs reliable data and clear rules. A while loop tests its condition before repeating the body. It can perform no iterations when the initial condition is already false.
Understand
A while loop tests its condition before repeating the body.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
The update must be reached. A continue placed before the update can accidentally create an endless loop.
While Loop
In Java, a while loop is used to repeat a block of code as long as a given condition remains true. It offers flexibility and control, especially when the number of iterations isn't known beforehand.
Syntax of Java while Loop
while (condition) {
// code block to execute
}
The loop checks the condition before every iteration. If the condition evaluates to true, the code block executes. Once the condition becomes false, the loop stops running.
Simple Example: Counting from 1 to 5
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation
Java · example discussed here
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}
}
Here, the loop starts with i = 1. The condition i <= 5 is checked before each iteration. As long as this is true, it prints the current value of i and increments it. When i becomes 6, the loop terminates.
Important: Infinite While Loop
If the condition never turns false, the loop keeps running indefinitely. This is called an infinite loop.
while (true) {
System.out.println("This loop runs forever!");
}
Be cautious with infinite loops. They're useful in some scenarios like real-time systems or game loops, but can also crash your program if misused.
Using while Loop to Iterate over an Array
public class ArrayWhileLoop {
public static void main(String[] args) {
int[] nums = {10, 20, 30, 40, 50};
int index = 0;
while (index < nums.length) {
System.out.println("Element at index " + index + ": " + nums[index]);
index++;
}
}
}
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Use Case: Validate User Input
The while loop is ideal when waiting for a correct user input:
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("yes")) {
System.out.print("Type 'yes' to continue: ");
input = scanner.nextLine();
}
System.out.println("Great! Moving forward...");
}
}
Type 'yes' to continue: no
Type 'yes' to continue: maybe
Type 'yes' to continue: yes
Great! Moving forward...
When Should You Use a while Loop?
- When the number of iterations is unknown
- When looping depends on dynamic conditions (user input, system state)
- To wait or retry until a condition is met
Common Mistakes to Avoid
- Forgetting to update the condition inside the loop (may cause infinite loop)
- Using
=instead of==for comparison - Modifying the loop variable in an unexpected way
Important boundaries and mistakes
The update must be reached. A continue placed before the update can accidentally create an endless loop.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: The update must be reached.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
int roll = 1;
while (roll <= 3) {
System.out.println(roll);
roll++;
}
}
}
Now change one thing: Start roll at 4. Predict the new behavior before checking the worked variation.
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
int roll = 1;
while (roll <= 3) {
System.out.println(roll);
roll++;
}
}
}
Expected output
1
2
3A while loop tests its condition before repeating the body. It can perform no iterations when the initial condition is already false.
The update must be reached. A continue placed before the update can accidentally create an endless loop.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Worked variation: Start roll at 4. The condition is false and no roll numbers print.
Check your understanding
What to remember
A while loop tests its condition before repeating the body. It can perform no iterations when the initial condition is already false. The update must be reached. A continue placed before the update can accidentally create an endless loop.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.