Java While Loop - Complete Guide
Introduction to While Loop
A while loop in Java repeatedly executes a block of code as long as a given boolean condition remains true. It is useful when the number of iterations is not known in advance and depends on runtime conditions.
While loops are commonly used for tasks such as reading input until a sentinel value is reached, waiting for a condition to change, or processing collections with custom stopping criteria.
Basic While Loop Syntax
The structure of a while loop uses the `while` keyword followed by a condition in parentheses. If the condition evaluates to true, the loop body executes. The condition is checked again after each iteration.
public class WhileLoop {
public static void main(String[] args) {
// Basic while loop
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++; // update loop variable
}
// Simulated user input attempts
int attempts = 0;
boolean accessGranted = false;
while (!accessGranted && attempts < 3) {
System.out.println("Attempt " + (attempts + 1) + ": Enter password");
attempts++;
if (attempts == 3) {
accessGranted = true;
System.out.println("Access granted!");
} else {
System.out.println("Invalid password. Try again.");
}
}
// Example with break statement
int number = 1;
while (true) {
System.out.println("Number: " + number);
number++;
if (number > 10) {
break; // exit the loop
}
}
}
}
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Attempt 1: Enter password Invalid password. Try again. Attempt 2: Enter password Invalid password. Try again. Attempt 3: Enter password Access granted! Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 Number: 8 Number: 9 Number: 10
While Loop with Collections and Arrays
While loops are often used to iterate over arrays and collections when you need explicit control over the index or want to remove elements safely using an iterator.
import java.util.ArrayList;
import java.util.Iterator;
public class WhileWithCollections {
public static void main(String[] args) {
// Iterating through an array
int[] numbers = {1, 2, 3, 4, 5};
int index = 0;
System.out.println("Array elements:");
while (index < numbers.length) {
System.out.println("numbers[" + index + "] = " + numbers[index]);
index++;
}
// Iterating through ArrayList
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
System.out.println("\nFruits:");
int fruitIndex = 0;
while (fruitIndex < fruits.size()) {
System.out.println(fruits.get(fruitIndex));
fruitIndex++;
}
// Using Iterator with while loop
System.out.println("\nFruits using Iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
if (fruit.equals("Orange")) {
iterator.remove();
}
}
System.out.println("\nFruits after removal:");
System.out.println(fruits);
// Searching for an element
ArrayList<Integer> values = new ArrayList<>();
values.add(10);
values.add(20);
values.add(30);
values.add(40);
values.add(50);
int searchValue = 30;
int searchIndex = 0;
boolean found = false;
while (searchIndex < values.size() && !found) {
if (values.get(searchIndex) == searchValue) {
found = true;
System.out.println("\nFound " + searchValue + " at index " + searchIndex);
}
searchIndex++;
}
if (!found) {
System.out.println("\nValue " + searchValue + " not found");
}
}
}
Array elements: numbers[0] = 1 numbers[1] = 2 numbers[2] = 3 numbers[3] = 4 numbers[4] = 5 Fruits: Apple Banana Orange Mango Fruits using Iterator: Apple Banana Orange Mango Fruits after removal: [Apple, Banana, Mango] Found 30 at index 2
Common Pitfalls and Best Practices
- ✅ Ensure the loop condition eventually becomes false to avoid infinite loops.
- ✅ Initialize loop variables before the while statement.
- ✅ Update loop variables inside the loop body.
- ✅ Use break statements sparingly to exit loops when necessary.
- ✅ Use a for loop when the number of iterations is predetermined.
- ✅ Use a while loop when the number of iterations depends on runtime conditions.
- ✅ Keep loop conditions clear and maintainable.
- ✅ Test with boundary cases to ensure correct loop behavior.