Verified for the 2025 AP Computer Science A exam•Citation:
Iteration is a fundamental programming concept that allows us to execute a block of code repeatedly. Rather than writing the same code multiple times, loops give us the power to repeat actions until a certain condition is met. The while
loop is one of Java's primary iteration structures, enabling programs to process data repeatedly, gather input, or perform calculations until specific criteria are satisfied. This guide explores how while loops work, their common applications, and how to use them effectively in your Java programs.
A while
loop repeatedly executes a block of code as long as a specified Boolean statement (condition) evaluates to true
. Once the condition becomes false
, the loop stops, and program execution continues with the code following the loop.
Components of a while loop:
while
keywordwhile (condition) { // Loop body - code to be repeated }
true
, the loop body executesfalse
, the loop terminates, and execution continues with the statement after the loop
(Counter: a variable that keeps track of a value, usually used to count or iterate through a loop.)int count = 1; while (count <= 5) { System.out.println("Count is: " + count); count++; // Increment the counter } System.out.println("Loop finished!");
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Loop finished!
A counter is a variable that keeps track of the number of iterations. This pattern is used when you need to perform an action a specific number of times:
int counter = 0; while (counter < 10) { System.out.println("Iteration: " + counter); counter++; }
A sentinel-controlled loop continues until it encounters a specific value (the sentinel):
import java.util.Scanner; public class SentinelExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter numbers to sum (enter -1 to stop):"); int sum = 0; int input = scanner.nextInt(); while (input != -1) { sum += input; input = scanner.nextInt(); } System.out.println("Sum: " + sum); scanner.close(); } }
A flag is a boolean variable that controls loop execution:
boolean found = false; // Flag initialization int[] numbers = {5, 10, 15, 20, 25}; int target = 15; int i = 0; while (i < numbers.length && !found) { if (numbers[i] == target) { found = true; // Set flag to true when target is found System.out.println("Found " + target + " at position " + i); } i++; } if (!found) { System.out.println(target + " not found in the array."); }
An infinite loop occurs when the loop condition never becomes false
. This is sometimes intentional but often a logical error:
// Intentional infinite loop while (true) { System.out.println("This will print forever unless interrupted"); // Usually needs a break statement or other mechanism to exit }
// Accidental infinite loop int counter = 1; while (counter > 0) { System.out.println("Current count: " + counter); counter++; // counter will never be <= 0, so the loop never ends }
To avoid accidental infinite loops:
false
A break statement immediately exits a loop, skipping any remaining iterations:
int i = 1; while (i <= 10) { System.out.println(i); if (i == 5) { System.out.println("Breaking the loop at 5"); break; // Exit the loop when i equals 5 } i++; }
A return statement inside a loop not only exits the loop but also exits the entire method:
public boolean containsValue(int[] array, int value) { int i = 0; while (i < array.length) { if (array[i] == value) { return true; // Immediately exits the method with true } i++; } return false; // Only reached if the value is not found }
The following example incorporates exception handling to catch invalid inputs. The try-catch
block handles the NumberFormatException that occurs if the user enters something that can't be parsed into an integer.
The Scanner class combined with while loops is perfect for validating user input:
import java.util.Scanner; public class InputValidation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int age = -1; while (age < 0 || age > 120) { System.out.print("Enter your age (0-120): "); try { age = Integer.parseInt(scanner.nextLine()); if (age < 0 || age > 120) { System.out.println("Age must be between 0 and 120."); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number."); } } System.out.println("Your age is: " + age); scanner.close(); } }
int sum = 0; int i = 1; while (i <= 100) { sum += i; i++; } System.out.println("Sum of numbers 1 to 100: " + sum);
Using the divisibility modulo operator (%
):
// Find the first 5 numbers divisible by both 4 and 7 int count = 0; int num = 1; while (count < 5) { if (num % 4 == 0 && num % 7 == 0) { System.out.println(num + " is divisible by both 4 and 7"); count++; } num++; }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReading { public static void main(String[] args) { try { File file = new File("data.txt"); Scanner fileScanner = new Scanner(file); while (fileScanner.hasNextLine()) { String data = fileScanner.nextLine(); System.out.println(data); } fileScanner.close(); } catch (FileNotFoundException e) { System.out.println("File not found."); } } }
A finally block in combination with exception handling can ensure resources are properly closed regardless of how the loop exits:
Scanner scanner = new Scanner(System.in); try { boolean validInput = false; while (!validInput) { try { System.out.print("Enter a positive number: "); int number = Integer.parseInt(scanner.nextLine()); if (number > 0) { System.out.println("You entered: " + number); validInput = true; } else { System.out.println("Number must be positive."); } } catch (NumberFormatException e) { System.out.println("That's not a valid number. Try again."); } } } finally { scanner.close(); // This will always execute, ensuring the scanner is closed }
While Java provides several types of loops, including the for loop, the while loop is particularly well-suited for certain scenarios:
Loop Type | Best Used When |
---|---|
while loop | Number of iterations is unknown beforehand |
for loop | Number of iterations is known or when iterating through collections |
// while loop for unknown number of iterations int sum = 0; int num = scanner.nextInt(); while (num != -1) { sum += num; num = scanner.nextInt(); } // for loop for known number of iterations int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; }
Forgetting to update the loop control variable
int i = 0; while (i < 10) { System.out.println(i); // Missing i++; creates an infinite loop }
Incorrect condition logic
// Intended to loop while i is less than 10 int i = 0; while (i > 10) { // Should be i < 10 // This loop body will never execute i++; }
Off-by-one errors
int i = 1; while (i < 10) { // Loops from 1 to 9, not 1 to 10 i++; } // To loop from 1 to 10: int i = 1; while (i <= 10) { i++; }
While loops are an essential tool for handling repetitive tasks and creating dynamic, responsive programs. By understanding their behavior and common patterns, you can use them effectively to solve a wide range of programming problems. In the next section, we'll explore for loops, which provide a more compact syntax for iteration when the number of repetitions is known beforehand.