Java for Loop


The for loop is one of the most commonly used control flow structures in Java. It provides a compact way to iterate over a sequence of values, perform repetitive tasks, and execute code a specific number of times. In this guide, we will explore how the for loop works in Java, its syntax, and various examples to help you understand its usage.

Table of Contents

  1. What is a Java for Loop?
  2. Syntax of the Java for Loop
  3. Types of for Loops in Java
  4. Java for Loop Example
  5. Nested for Loops
  6. Best Practices for Using the for Loop

What is a Java for Loop?

The for loop is a control flow statement that is used to repeatedly execute a block of code a fixed number of times. It is commonly used when the number of iterations is known beforehand. The loop iterates over a range of values, typically incrementing or decrementing a counter variable until a specified condition is met.


Syntax of the Java for Loop

The syntax of the for loop consists of three parts:

  1. Initialization: Sets the starting value of the loop control variable.
  2. Condition: A boolean expression that is checked before each iteration. The loop runs as long as the condition is true.
  3. Update: Updates the loop control variable after each iteration.

Here is the general syntax of the for loop in Java:

for (initialization; condition; update) {
    // block of code to be executed
}
  • Initialization: Typically initializes a counter variable (e.g., int i = 0).
  • Condition: A boolean expression (e.g., i < 5). The loop continues as long as the condition is true.
  • Update: Modifies the loop control variable (e.g., i++ to increment).

Types of for Loops in Java

Simple for Loop

The traditional for loop is used when you know the exact number of iterations.

Syntax:

for (int i = 0; i < 5; i++) {
    // code to be executed
}

Enhanced for Loop (for-each loop)

The enhanced for loop (also called the for-each loop) simplifies iteration over collections, arrays, or other iterable data structures. It eliminates the need for an index counter and makes the code more readable.

Syntax:

for (type element : array_or_collection) {
    // code to be executed for each element
}

The enhanced for loop is especially useful when you need to iterate through arrays or collections without modifying the index.


Java for Loop Example

Let’s take a look at some examples to understand how the for loop works in Java.

Example 1: Printing Numbers 1 to 5

public class ForLoopExample {
    public static void main(String[] args) {
        // Simple for loop to print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Explanation:

  • The loop starts with i = 1.
  • The condition i <= 5 ensures the loop runs until i reaches 5.
  • After each iteration, i is incremented (i++).

Output:

1
2
3
4
5

Example 2: Sum of Numbers

public class ForLoopSumExample {
    public static void main(String[] args) {
        int sum = 0;
        
        // Using the for loop to calculate the sum of numbers from 1 to 10
        for (int i = 1; i <= 10; i++) {
            sum += i;  // Add the value of i to sum
        }
        
        System.out.println("Sum of numbers from 1 to 10: " + sum);
    }
}

Explanation:

  • This program calculates the sum of numbers from 1 to 10 using a for loop.
  • The variable sum accumulates the total sum.

Output:

Sum of numbers from 1 to 10: 55

Example 3: Iterating Through an Array

public class ForLoopArrayExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Enhanced for loop to iterate through the array and print each number
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}

Explanation:

  • Here, the enhanced for loop is used to iterate through the array numbers.
  • Each element of the array is printed during each iteration.

Output:

10
20
30
40
50

Nested for Loops

A nested for loop is when you use one for loop inside another. This is useful for iterating over multi-dimensional arrays or when you need to perform more complex operations with multiple loops.

Example: Multiplication Table

public class NestedForLoopExample {
    public static void main(String[] args) {
        // Print multiplication table of 1 to 5
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.print(i * j + "\t"); // Print the product of i and j
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

Explanation:

  • The outer loop controls the rows (numbers 1 through 5).
  • The inner loop controls the columns, printing the product of the outer loop variable i and inner loop variable j.

Output:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

Best Practices for Using the for Loop

  1. Use meaningful variable names: For clarity, use meaningful names for the loop control variable (e.g., i, j, count).
  2. Avoid infinite loops: Ensure the loop’s condition eventually evaluates to false to prevent infinite loops.
  3. Limit nested loops: Too many nested loops can make your code hard to read and maintain. Try to optimize your logic where possible.
  4. Use the enhanced for loop for arrays and collections: The enhanced for loop is ideal for iterating through collections and arrays where you don't need to manipulate the index.