Loops are control flow statements that allow you to execute a block of code repeatedly based on a condition. They are fundamental to programming and help avoid code duplication. Java provides four types of loops: for, while, do-while, and the enhanced for-each loop. Each loop type is suited for different scenarios, and choosing the right one makes your code more readable and efficient.
Loops are essential for tasks like iterating through arrays, processing collections, repeating operations until a condition is met, and implementing algorithms. Understanding when and how to use each loop type is crucial for writing clean, efficient Java code.
The for loop is used when you know exactly how many times you want to iterate. It consists of three parts: initialization, condition, and update expression. All three parts are optional, but the semicolons are required.
public class ForLoop {
public static void main(String[] args) {
// Basic for loop - print 1 to 5
System.out.println("--- Basic for loop ---");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " "); // 1 2 3 4 5
}
System.out.println();
// Counting backwards
System.out.println("--- Countdown ---");
for (int i = 5; i >= 1; i--) {
System.out.print(i + " "); // 5 4 3 2 1
}
System.out.println();
// Step by 2
System.out.println("--- Even numbers ---");
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " "); // 0 2 4 6 8 10
}
System.out.println();
// Multiple variables
System.out.println("--- Multiple variables ---");
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}
// Infinite loop (use with caution!)
// for (;;) {
// System.out.println("This runs forever!");
// break; // Need break to exit
// }
// Array iteration with for loop
System.out.println("--- Array iteration ---");
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
}
}
The while loop executes a block of code as long as the condition is true. The condition is checked before each iteration, so the loop body may never execute if the condition is initially false. Use while when you don't know in advance how many iterations are needed.
import java.util.Scanner;
public class WhileLoop {
public static void main(String[] args) {
// Basic while loop
System.out.println("--- Basic while loop ---");
int n = 1;
while (n <= 5) {
System.out.print(n + " "); // 1 2 3 4 5
n++;
}
System.out.println();
// Sum of numbers
System.out.println("--- Sum 1 to 10 ---");
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++;
}
System.out.println("Sum: " + sum); // 55
// Reading input until condition met
Scanner scanner = new Scanner(System.in);
System.out.println("--- Enter numbers (0 to stop) ---");
int num = -1;
while (num != 0) {
System.out.print("Enter number: ");
num = scanner.nextInt();
if (num != 0) {
System.out.println("You entered: " + num);
}
}
System.out.println("Loop ended!");
// Finding factorial
System.out.println("--- Factorial of 5 ---");
int factorial = 1;
int number = 5;
int temp = number;
while (temp > 0) {
factorial *= temp;
temp--;
}
System.out.println(number + "! = " + factorial); // 120
scanner.close();
}
}
The do-while loop is similar to while, but it checks the condition after executing the loop body. This guarantees that the loop body executes at least once, even if the condition is initially false. It's commonly used for menu-driven programs and input validation.
import java.util.Scanner;
public class DoWhileLoop {
public static void main(String[] args) {
// Basic do-while - executes at least once
System.out.println("--- Basic do-while ---");
int x = 1;
do {
System.out.print(x + " "); // 1 2 3 4 5
x++;
} while (x <= 5);
System.out.println();
// Executes once even if condition is false
System.out.println("--- Condition false from start ---");
int y = 10;
do {
System.out.println("This prints once: y = " + y);
} while (y < 5); // Condition is false, but body executed once
// Menu-driven program (common use case)
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Menu ---");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("You selected Option 1");
break;
case 2:
System.out.println("You selected Option 2");
break;
case 3:
System.out.println("You selected Option 3");
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 0);
// Input validation
int age;
do {
System.out.print("Enter your age (1-120): ");
age = scanner.nextInt();
if (age < 1 || age > 120) {
System.out.println("Invalid age! Try again.");
}
} while (age < 1 || age > 120);
System.out.println("Valid age entered: " + age);
scanner.close();
}
}
The enhanced for loop (also called for-each loop) was introduced in Java 5. It provides a cleaner syntax for iterating over arrays and collections without needing an index variable. It's read-only - you cannot modify the array elements using this loop.
import java.util.*;
public class ForEachLoop {
public static void main(String[] args) {
// Basic for-each with array
System.out.println("--- Array iteration ---");
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.print(num + " "); // 10 20 30 40 50
}
System.out.println();
// String array
System.out.println("--- String array ---");
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println("Hello, " + name + "!");
}
// ArrayList
System.out.println("--- ArrayList ---");
ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 2D array
System.out.println("--- 2D array ---");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int[] tl-row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
// Limitation: Cannot modify array elements
System.out.println("--- Cannot modify with for-each ---");
int[] arr = {1, 2, 3, 4, 5};
// This doesn't modify the array!
for (int num : arr) {
num = num * 2; // Only modifies local variable
}
System.out.println("Array unchanged: " + Arrays.toString(arr));
// Use regular for loop to modify
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2; // This modifies the array
}
System.out.println("Array modified: " + Arrays.toString(arr));
}
}
The break statement exits the loop immediately, while continue skips the current iteration and moves to the next one. These statements provide fine-grained control over loop execution.
public class BreakContinue {
public static void main(String[] args) {
// break - exits loop immediately
System.out.println("--- break example ---");
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i is 6
}
System.out.print(i + " "); // 1 2 3 4 5
}
System.out.println("\nLoop ended at i=6");
// continue - skips current iteration
System.out.println("\n--- continue example (skip evens) ---");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.print(i + " "); // 1 3 5 7 9
}
System.out.println();
// Finding first occurrence
System.out.println("\n--- Find first negative ---");
int[] numbers = {5, 10, -3, 8, -7, 12};
int firstNegative = 0;
for (int num : numbers) {
if (num < 0) {
firstNegative = num;
break; // Found it, exit loop
}
}
System.out.println("First negative: " + firstNegative);
// Labeled break (for nested loops)
System.out.println("\n--- Labeled break ---");
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer; // Breaks out of both loops
}
System.out.println("i=" + i + ", j=" + j);
}
}
// Labeled continue
System.out.println("\n--- Labeled continue ---");
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer; // Skip to next iteration of outer loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop. Nested loops are commonly used for working with 2D arrays, matrices, and generating patterns.
public class NestedLoops {
public static void main(String[] args) {
// Multiplication tl-table
System.out.println("--- 5x5 Multiplication tl-table ---");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Pattern printing - right triangle
System.out.println("\n--- Right Triangle Pattern ---");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern printing - pyramid
System.out.println("\n--- Pyramid Pattern ---");
int rows = 5;
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
// 2D array traversal
System.out.println("\n--- 2D Array Sum ---");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
System.out.println("Sum of all elements: " + sum); // 45
// Finding element in 2D array
System.out.println("\n--- Search in 2D Array ---");
int target = 5;
boolean found = false;
outerLoop: for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
System.out.println("Found " + target + " at [" + i + "][" + j + "]");
found = true;
break outerLoop;
}
}
}
if (!found) {
System.out.println(target + " not found");
}
}
}
| Loop Type | When to Use | Condition Check | Minimum Executions |
|---|---|---|---|
| for | Known number of iterations | Before each iteration | 0 |
| while | Unknown iterations, condition-based | Before each iteration | 0 |
| do-while | At least one execution needed | After each iteration | 1 |
| for-each | Iterating arrays/collections | Automatic | 0 |
| Pattern | Code | Use Case |
|---|---|---|
| Count up | for (int i = 0; i < n; i++) | Standard iteration |
| Count down | for (int i = n; i >= 0; i--) | Reverse iteration |
| Step by n | for (int i = 0; i < n; i += 2) | Skip elements |
| Array iteration | for (int i = 0; i < arr.length; i++) | Access by index |
| For-each | for (Type item : collection) | Read-only iteration |
| Infinite loop | while (true) or for (;;) | Server loops, games |
Explore 500+ free tutorials across 20+ languages and frameworks.