The while
loop in Java is a control flow statement that repeatedly executes a block of code as long as a given condition is true
. It’s particularly useful for situations where you do not know beforehand how many times you need to iterate. Below are examples demonstrating various uses of the while
loop, complete with explanations and comments for clarity.
Basic while
Loop
A basic while
loop example that prints numbers from 1 to 5.
1 2 3 4 5 6 7 8 9 10 11 |
int i = 1; // Initialization while (i <= 5) { // Condition System.out.println(i); i++; // Increment } // Output: // 1 // 2 // 3 // 4 // 5 |
In this example, the loop continues to execute as long as i
is less than or equal to 5. The variable i
is incremented in each iteration, ensuring the loop eventually terminates.
Infinite while
Loop
An infinite loop occurs when the condition never becomes false. Use with caution!
1 2 3 4 5 |
while (true) { System.out.println("Infinite loop"); break; // To prevent the infinite loop, we break out of it. } // Output: Infinite loop |
Here, the condition is always true, creating an infinite loop. The break
statement is used to exit the loop safely.
while
Loop for Reading User Input
The while
loop can be used to read user input until a certain condition is met. In this example, it reads input until the user enters “exit”.
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Scanner; Scanner scanner = new Scanner(System.in); String input = ""; while (!input.equals("exit")) { System.out.println("Enter a string: "); input = scanner.nextLine(); System.out.println("You entered: " + input); } scanner.close(); // Output varies based on user input. Loop terminates when user inputs "exit". |
Using while
Loop for Array Iteration
Although for-each and for loops are more commonly used for arrays, you can use a while
loop to iterate through an array.
1 2 3 4 5 6 7 8 9 10 |
String[] fruits = {"Apple", "Banana", "Cherry"}; int index = 0; // Array index starts at 0 while (index < fruits.length) { System.out.println(fruits[index]); index++; } // Output: // Apple // Banana // Cherry |
while
Loop with Break and Continue
The break
statement can exit a loop, and continue
can skip to the next iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
int num = 0; while (num < 10) { if (num == 5) { num++; continue; // Skips the rest of the loop body when num is 5 } if (num == 8) { break; // Exits the loop when num reaches 8 } System.out.println(num); num++; } // Output: // 0 // 1 // 2 // 3 // 4 // 6 // 7 |
In this example, when num
is 5, the loop skips printing the number by using continue
, and when num
reaches 8, it exits the loop with break
, preventing 8 from being printed.
The while
loop is a versatile tool in Java, offering the flexibility to handle repetitive tasks with dynamic conditions. Through these examples, you can see the wide range of applications for while
loops, from simple counting to controlling program flow based on user input or other runtime conditions.