while Loop
Repeat code while a condition is true - ideal when the number of iterations is not known in advance.
Overview
Key Points
- •Syntax: while (condition) { ... } - condition checked before each iteration
- •If condition is false at the start, the body never executes (zero iterations)
- •The body must eventually change the condition to false, or you get an infinite loop
- •Common pattern: while (scanner.hasNextInt()) - process until input ends
- •while is preferred over for when the number of iterations is unknown beforehand
- •Use a flag variable (boolean running = true;) to control complex loop exit conditions
Examples
Count up with while
public class Main {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++; // update - must be inside the body!
}
System.out.println("Done");
}
}The update (count++) is inside the body. Forgetting it creates an infinite loop.
Input validation loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = -1;
while (number < 1 || number > 10) {
System.out.print("Enter a number between 1 and 10: ");
number = sc.nextInt();
if (number < 1 || number > 10) {
System.out.println("Invalid! Try again.");
}
}
System.out.println("You entered: " + number);
sc.close();
}
}This loop keeps asking until valid input is received - classic "input validation" pattern.
Finding the first power of 2 greater than 1000
public class Main {
public static void main(String[] args) {
int power = 1;
while (power <= 1000) {
power *= 2;
}
System.out.println("First power of 2 > 1000: " + power); // 1024
}
}The loop count is unknown in advance - this is exactly when while outshines for.
Common Mistakes
- Infinite loop: condition never becomes false because the variable inside it is never updated
- Unreachable code after an infinite while(true) loop - the compiler may warn about this
- Checking condition before any value is set: initialise the variable to a value that guarantees at least one iteration when needed
Note
A while(true) loop with a break statement inside is a common pattern for menus and game loops: while (true) { ... if (quit) break; }. This makes the exit condition explicit and visible.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4