Java Loops - Complete Tutorial
Master Java loops: Learn for, while, do-while loops, nested loops, break, continue statements, and for-each loops with practical examples and best practices for efficient iteration.
3 Loop Types
for, while, do-while
Nested Loops
Multi-dimensional iteration
Control Statements
break & continue
Enhanced Loop
for-each for collections
1. Introduction to Java Loops
Loops in Java are control flow statements that allow you to execute a block of code repeatedly until a specific condition is met. They are essential for tasks that require repetition, such as processing arrays, collections, or performing calculations iteratively.
Why Use Loops?
- Code Reusability: Write once, execute many times
- Efficiency: Reduce code duplication
- Readability: Cleaner, more organized code
- Dynamic Execution: Handle variable data sizes
- Data Processing: Iterate through arrays/collections
- Automation: Repeat tasks without manual intervention
Types of Java Loops
- for loop: Fixed number of iterations
- while loop: Condition-based iteration
- do-while loop: Execute at least once
- Enhanced for-each loop: For arrays/collections
- Nested loops: Loop inside another loop
- Infinite loops: Run indefinitely (use with caution)
Loop Control Flow
All loops follow a basic pattern: Initialize → Test Condition → Execute Body → Update → Repeat. Understanding this flow is key to mastering loops.
Loop Flow Diagram
Start Loop
│
▼
Initialize Counter
│
▼
Check Condition
│
├─────────▶ Condition TRUE ──────▶ Execute Loop Body
│ │
│ ▼
│ Update Counter
│ │
│ ▼
└─────────▶ Condition FALSE ←───────┘
│
▼
Exit Loop
2. The 'for' Loop
The for loop is used when you know exactly how many times you want to execute a block of code. It has three parts: initialization, condition, and increment/decrement.
public class ForLoopExample {
public static void main(String[] args) {
// Basic for loop - print numbers 1 to 10
System.out.println("=== Basic for loop ===");
for(int i = 1; i <= 10; i++) {
System.out.println("Number: " + i);
}
// Countdown from 10 to 1
System.out.println("\n=== Countdown ===");
for(int i = 10; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
// Loop with step of 2
System.out.println("\n=== Even numbers 1 to 20 ===");
for(int i = 2; i <= 20; i += 2) {
System.out.println("Even: " + i);
}
// Sum of numbers from 1 to 100
System.out.println("\n=== Sum calculation ===");
int sum = 0;
for(int i = 1; i <= 100; i++) {
sum += i; // sum = sum + i
}
System.out.println("Sum of 1 to 100 = " + sum);
// Factorial calculation
System.out.println("\n=== Factorial calculation ===");
int number = 5;
int factorial = 1;
for(int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(number + "! = " + factorial);
// Multiple variables in for loop
System.out.println("\n=== Multiple variables ===");
for(int i = 0, j = 10; i <= 10; i++, j--) {
System.out.println("i = " + i + ", j = " + j);
}
// Infinite for loop (commented out - dangerous!)
// for(;;) {
// System.out.println("This will run forever!");
// }
}
}
| Part | Description | Example | Optional? |
|---|---|---|---|
| Initialization | Executes once before loop starts | int i = 0 |
Yes (can be outside) |
| Condition | Checked before each iteration | i < 10 |
No (but can use true) |
| Update | Executes after each iteration | i++ |
Yes (can be in body) |
Standard Basic for Loop
for(int i=0; i<10; i++)
Reverse Countdown Loop
for(int i=10; i>0; i--)
Step Custom Increment
for(int i=0; i<100; i+=5)
3. The 'while' Loop
The while loop repeats a block of code as long as a specified condition is true. The condition is checked before the loop body executes.
import java.util.Scanner;
public class WhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Basic while loop - count from 1 to 5
System.out.println("=== Basic while loop ===");
int count = 1;
while(count <= 5) {
System.out.println("Count: " + count);
count++; // Don't forget to update!
}
// User input validation
System.out.println("\n=== Input validation ===");
int number;
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
while(number <= 0) {
System.out.print("Invalid! Enter a positive number: ");
number = scanner.nextInt();
}
System.out.println("Valid number entered: " + number);
// Sum until user enters 0
System.out.println("\n=== Sum calculator (enter 0 to stop) ===");
int sum = 0;
int input;
System.out.print("Enter a number (0 to stop): ");
input = scanner.nextInt();
while(input != 0) {
sum += input;
System.out.print("Enter another number (0 to stop): ");
input = scanner.nextInt();
}
System.out.println("Total sum: " + sum);
// Reverse a number
System.out.println("\n=== Reverse a number ===");
int original = 12345;
int reversed = 0;
int temp = original;
while(temp != 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp = temp / 10;
}
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
// Fibonacci sequence using while loop
System.out.println("\n=== Fibonacci sequence ===");
int n = 10;
int first = 0, second = 1;
int i = 0;
System.out.print("Fibonacci: ");
while(i < n) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
i++;
}
scanner.close();
}
}
- Always initialize loop control variable before while loop
- Ensure the condition will eventually become false (avoid infinite loops)
- Update loop control variable inside the loop body
- Use while loops when number of iterations is unknown
- Prefer while loops for reading files or streams until EOF
When to Use while Loop
- Reading user input until valid
- Processing files until end
- Game loops (until game over)
- Menu-driven programs
- When iterations depend on runtime conditions
Common while Loop Errors
- Forgetting to update loop variable (infinite loop)
- Using wrong condition (off-by-one errors)
- Not initializing loop variable
- Using = instead of == in condition
- Complex conditions that are hard to debug
4. The 'do-while' Loop
The do-while loop is similar to while loop, but it guarantees at least one execution of the loop body because the condition is checked after the body executes.
import java.util.Scanner;
public class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Basic do-while loop
System.out.println("=== Basic do-while loop ===");
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while(count <= 5);
// Menu-driven program (perfect for do-while)
System.out.println("\n=== Menu-driven Calculator ===");
int choice;
double num1, num2, result;
do {
System.out.println("\n=== Calculator Menu ===");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
choice = scanner.nextInt();
if(choice >= 1 && choice <= 4) {
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
switch(choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if(num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero!");
}
break;
}
} else if(choice != 5) {
System.out.println("Invalid choice! Please try again.");
}
} while(choice != 5);
System.out.println("Thank you for using Calculator!");
// Password validation
System.out.println("\n=== Password validation ===");
String password;
boolean isValid = false;
do {
System.out.print("Enter password (min 8 chars): ");
password = scanner.next();
if(password.length() >= 8) {
isValid = true;
System.out.println("Password accepted!");
} else {
System.out.println("Password too short! Try again.");
}
} while(!isValid);
// Guaranteed execution example
System.out.println("\n=== Guaranteed execution ===");
int x = 10;
do {
System.out.println("This will print even though x > 5 is false from start");
System.out.println("x = " + x);
} while(x < 5); // Condition false initially
scanner.close();
}
}
| Feature | while Loop | do-while Loop |
|---|---|---|
| Condition Check | Before loop body | After loop body |
| Minimum Executions | Zero (if false initially) | One (always executes once) |
| Use Case | When iterations may be zero | When at least one iteration needed |
| Syntax | while(condition) { ... } |
do { ... } while(condition); |
| Semicolon | Not required after while | Required after while(condition) |
| Example | Validating input before processing | Menu systems, password validation |
5. Enhanced 'for-each' Loop
The enhanced for loop (for-each) simplifies iteration through arrays and collections. It automatically handles iteration without needing an index variable.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForEachLoopExample {
public static void main(String[] args) {
// Array iteration with for-each
System.out.println("=== Array iteration ===");
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Array elements:");
for(int num : numbers) {
System.out.println(num);
}
// Sum of array elements
int sum = 0;
for(int num : numbers) {
sum += num;
}
System.out.println("Sum of array: " + sum);
// String array
System.out.println("\n=== String array ===");
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
for(String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// ArrayList iteration
System.out.println("\n=== ArrayList iteration ===");
List colors = new ArrayList<>(Arrays.asList(
"Red", "Green", "Blue", "Yellow", "Purple"
));
System.out.println("Colors:");
for(String color : colors) {
System.out.println("- " + color);
}
// 2D array with for-each
System.out.println("\n=== 2D Array iteration ===");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Matrix elements:");
for(int[] row : matrix) {
for(int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
// Find maximum in array
System.out.println("\n=== Find maximum ===");
int[] values = {45, 12, 89, 34, 67, 23};
int max = values[0];
for(int value : values) {
if(value > max) {
max = value;
}
}
System.out.println("Maximum value: " + max);
// Limitations of for-each
System.out.println("\n=== Limitations ===");
System.out.println("Cannot modify array elements directly:");
int[] nums = {1, 2, 3, 4, 5};
System.out.println("Original: " + Arrays.toString(nums));
// This won't modify the original array
for(int num : nums) {
num = num * 2; // Changes local copy only
}
System.out.println("After attempt to double: " + Arrays.toString(nums));
// To modify, use traditional for loop
for(int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * 2;
}
System.out.println("After traditional loop: " + Arrays.toString(nums));
}
}
Advantages of for-each
- Simpler syntax - no index management
- Prevents index-related errors
- More readable for simple iterations
- Works with all Iterable collections
- No risk of index out of bounds
- Automatic type inference
Limitations of for-each
- Cannot modify array elements directly
- No access to index (use counter variable)
- Cannot iterate backwards
- Cannot skip elements (no continue to specific index)
- Only forward iteration
- Not suitable for parallel iteration
6. Nested Loops
Nested loops are loops inside other loops. They are useful for working with multi-dimensional data like matrices, tables, or generating patterns.
public class NestedLoopsExample {
public static void main(String[] args) {
// Basic nested for loops - multiplication table
System.out.println("=== Multiplication Table (1-10) ===");
for(int i = 1; i <= 10; i++) {
for(int j = 1; j <= 10; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Pattern 1: Right triangle
System.out.println("\n=== Right Triangle Pattern ===");
int rows = 5;
for(int i = 1; i <= rows; i++) {
for(int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern 2: Inverted triangle
System.out.println("\n=== Inverted Triangle ===");
for(int i = rows; i >= 1; i--) {
for(int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern 3: Pyramid
System.out.println("\n=== Pyramid Pattern ===");
for(int i = 1; i <= rows; i++) {
// Print spaces
for(int j = rows; j > i; j--) {
System.out.print(" ");
}
// Print stars
for(int k = 1; k <= (2 * i - 1); k++) {
System.out.print("*");
}
System.out.println();
}
// 2D array processing
System.out.println("\n=== 2D Array Processing ===");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Matrix:");
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Sum of each row
System.out.println("\n=== Row-wise Sum ===");
for(int i = 0; i < matrix.length; i++) {
int rowSum = 0;
for(int j = 0; j < matrix[i].length; j++) {
rowSum += matrix[i][j];
}
System.out.println("Sum of row " + (i+1) + ": " + rowSum);
}
// Transpose of matrix
System.out.println("\n=== Transpose of Matrix ===");
int[][] transpose = new int[3][3];
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Transpose:");
for(int i = 0; i < transpose.length; i++) {
for(int j = 0; j < transpose[i].length; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
// Different loop types nested
System.out.println("\n=== Mixed Nested Loops ===");
int outer = 1;
while(outer <= 3) {
System.out.println("Outer loop: " + outer);
for(int inner = 1; inner <= 2; inner++) {
System.out.println(" Inner for loop: " + inner);
}
outer++;
}
}
}
- Single loop: O(n) - linear time
- Two nested loops: O(n²) - quadratic time
- Three nested loops: O(n³) - cubic time
- Important: Deep nesting can cause performance issues
- Tip: Avoid unnecessary nesting; break complex loops into methods
- Rule of thumb: If nesting exceeds 3 levels, reconsider your algorithm
7. Loop Control: break and continue
The break and continue statements provide additional control over loop execution. break exits the loop entirely, while continue skips to the next iteration.
public class BreakExample {
public static void main(String[] args) {
// Simple break example
System.out.println("=== Simple break ===");
for(int i = 1; i <= 10; i++) {
if(i == 5) {
System.out.println("Breaking at i = " + i);
break; // Exit loop when i == 5
}
System.out.println("i = " + i);
}
// Break in while loop
System.out.println("\n=== Break in while loop ===");
int num = 1;
while(true) { // Infinite loop
System.out.println("Number: " + num);
num++;
if(num > 5) {
System.out.println("Breaking infinite loop");
break;
}
}
// Search in array
System.out.println("\n=== Search in array ===");
int[] numbers = {12, 45, 23, 67, 89, 34, 56};
int searchValue = 67;
boolean found = false;
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] == searchValue) {
System.out.println("Found " + searchValue + " at index " + i);
found = true;
break; // Stop searching once found
}
}
if(!found) {
System.out.println(searchValue + " not found in array");
}
// Break with nested loops
System.out.println("\n=== Break with nested loops ===");
for(int i = 1; i <= 3; i++) {
System.out.println("Outer loop: " + i);
for(int j = 1; j <= 3; j++) {
if(j == 2) {
break; // Breaks only inner loop
}
System.out.println(" Inner loop: " + j);
}
}
// Labeled break (rarely used)
System.out.println("\n=== Labeled break ===");
outerLoop:
for(int i = 1; i <= 3; i++) {
System.out.println("Outer: " + i);
for(int j = 1; j <= 3; j++) {
if(i == 2 && j == 2) {
System.out.println("Breaking both loops");
break outerLoop; // Breaks outer loop
}
System.out.println(" Inner: " + j);
}
}
}
}
public class ContinueExample {
public static void main(String[] args) {
// Simple continue example
System.out.println("=== Skip even numbers ===");
for(int i = 1; i <= 10; i++) {
if(i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}
// Continue in while loop
System.out.println("\n=== Skip numbers divisible by 3 ===");
int num = 1;
while(num <= 10) {
if(num % 3 == 0) {
num++;
continue; // Skip to next iteration
}
System.out.println("Number not divisible by 3: " + num);
num++;
}
// Process array, skip invalid values
System.out.println("\n=== Process array (skip negatives) ===");
int[] values = {10, -5, 20, -3, 30, -8, 40};
int sum = 0;
for(int value : values) {
if(value < 0) {
System.out.println("Skipping negative value: " + value);
continue;
}
sum += value;
}
System.out.println("Sum of positive values: " + sum);
// Continue with nested loops
System.out.println("\n=== Continue in nested loops ===");
for(int i = 1; i <= 3; i++) {
System.out.println("Outer loop: " + i);
for(int j = 1; j <= 3; j++) {
if(j == 2) {
continue; // Skip j == 2 in inner loop
}
System.out.println(" Inner loop: " + j);
}
}
// Practical example: Data validation
System.out.println("\n=== Data validation example ===");
String[] data = {"apple", "", "banana", null, "cherry", " "};
System.out.println("Valid strings:");
for(String item : data) {
if(item == null || item.trim().isEmpty()) {
continue; // Skip null or empty strings
}
System.out.println("- " + item);
}
// Labeled continue (rarely used)
System.out.println("\n=== Labeled continue ===");
outerLoop:
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
if(i == 2 && j == 2) {
System.out.println("Skipping to next outer iteration");
continue outerLoop;
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
| Statement | Purpose | Effect | Common Use Cases |
|---|---|---|---|
break |
Exit loop immediately | Jumps to first statement after loop | Search algorithms, error conditions, early termination |
continue |
Skip current iteration | Jumps to next iteration of loop | Filtering data, skipping invalid values, conditional processing |
break label |
Exit labeled loop | Jumps out of nested loops | Complex nested loop termination |
continue label |
Continue labeled loop | Jumps to next iteration of outer loop | Skipping iterations in nested loops |
8. Practical Loop Examples
Example 1: Number Guessing Game
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secretNumber = random.nextInt(100) + 1; // 1 to 100
int attempts = 0;
final int MAX_ATTEMPTS = 7;
boolean guessed = false;
System.out.println("=== Number Guessing Game ===");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("You have " + MAX_ATTEMPTS + " attempts to guess it.");
for(attempts = 1; attempts <= MAX_ATTEMPTS; attempts++) {
System.out.print("\nAttempt " + attempts + "/" + MAX_ATTEMPTS + ": ");
System.out.print("Enter your guess: ");
int guess;
try {
guess = scanner.nextInt();
} catch(Exception e) {
System.out.println("Invalid input! Please enter a number.");
scanner.next(); // Clear invalid input
attempts--; // Don't count this as an attempt
continue;
}
if(guess < 1 || guess > 100) {
System.out.println("Please guess between 1 and 100.");
attempts--; // Don't count this as an attempt
continue;
}
if(guess == secretNumber) {
System.out.println("🎉 Congratulations! You guessed it!");
System.out.println("The number was " + secretNumber);
System.out.println("You found it in " + attempts + " attempts.");
guessed = true;
break;
} else if(guess < secretNumber) {
System.out.println("Too low! Try a higher number.");
} else {
System.out.println("Too high! Try a lower number.");
}
// Give hint after 3 attempts
if(attempts == 3) {
if(secretNumber % 2 == 0) {
System.out.println("💡 Hint: The number is even.");
} else {
System.out.println("💡 Hint: The number is odd.");
}
}
}
if(!guessed) {
System.out.println("\n😞 Game Over! You've used all " + MAX_ATTEMPTS + " attempts.");
System.out.println("The secret number was: " + secretNumber);
}
scanner.close();
}
}
Example 2: Student Grade Calculator
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== Student Grade Calculator ===");
System.out.print("Enter number of students: ");
int numStudents = scanner.nextInt();
// Arrays to store data
String[] names = new String[numStudents];
double[] grades = new double[numStudents];
// Input loop
for(int i = 0; i < numStudents; i++) {
System.out.println("\n--- Student " + (i+1) + " ---");
System.out.print("Enter student name: ");
scanner.nextLine(); // Clear buffer
names[i] = scanner.nextLine();
// Input validation loop for grade
while(true) {
System.out.print("Enter grade (0-100): ");
grades[i] = scanner.nextDouble();
if(grades[i] >= 0 && grades[i] <= 100) {
break; // Valid grade, exit validation loop
} else {
System.out.println("Invalid grade! Please enter between 0 and 100.");
}
}
}
// Calculate statistics
double total = 0;
double highest = grades[0];
double lowest = grades[0];
String topStudent = names[0];
String bottomStudent = names[0];
for(int i = 0; i < numStudents; i++) {
total += grades[i];
if(grades[i] > highest) {
highest = grades[i];
topStudent = names[i];
}
if(grades[i] < lowest) {
lowest = grades[i];
bottomStudent = names[i];
}
}
double average = total / numStudents;
// Count grades by category
int excellent = 0, good = 0, averageCount = 0, fail = 0;
for(double grade : grades) {
if(grade >= 90) {
excellent++;
} else if(grade >= 70) {
good++;
} else if(grade >= 50) {
averageCount++;
} else {
fail++;
}
}
// Display results
System.out.println("\n=== Grade Report ===");
System.out.println("Total students: " + numStudents);
System.out.printf("Class average: %.2f\n", average);
System.out.println("Highest grade: " + highest + " (" + topStudent + ")");
System.out.println("Lowest grade: " + lowest + " (" + bottomStudent + ")");
System.out.println("\nGrade Distribution:");
System.out.println("Excellent (90-100): " + excellent + " students");
System.out.println("Good (70-89): " + good + " students");
System.out.println("Average (50-69): " + averageCount + " students");
System.out.println("Fail (0-49): " + fail + " students");
// Display individual grades
System.out.println("\n=== Individual Grades ===");
System.out.println("Name\t\tGrade\t\tStatus");
System.out.println("-----------------------------------");
for(int i = 0; i < numStudents; i++) {
String status;
if(grades[i] >= 90) status = "Excellent";
else if(grades[i] >= 70) status = "Good";
else if(grades[i] >= 50) status = "Average";
else status = "Fail";
System.out.printf("%-15s %-10.2f %-10s\n",
names[i], grades[i], status);
}
scanner.close();
}
}
9. Loop Best Practices and Common Mistakes
- Infinite loops: Forgetting to update loop variable
- Off-by-one errors: Using
<=instead of< - Modifying loop variable: Changing index inside for loop body
- Using wrong loop type: for when while is better, or vice versa
- Nested loop complexity: Creating O(n³) algorithms unnecessarily
- Not using enhanced for: When simple iteration is needed
Loop Best Practices
- Use for when iterations are known
- Use while for condition-based iteration
- Use do-while when code must execute at least once
- Prefer for-each for simple array/collection traversal
- Keep loop bodies small (extract to methods if needed)
- Avoid deep nesting (max 2-3 levels)
- Use meaningful loop variable names (
i, j, kare OK for simple loops)
Performance Tips
- Cache array length:
for(int i=0; ivs int len = array.length; for(int i=0; i - Avoid method calls in loop conditions
- Use
StringBuilderinstead of string concatenation in loops - Minimize operations inside inner loops
- Consider algorithm complexity before implementing nested loops
- Use
breakearly when possible
Choosing the Right Loop
Use for loop when: You know exact number of iterations
Use while loop when: Iterations depend on runtime condition
Use do-while when: You need at least one execution
Use for-each when: Simply traversing arrays/collections