Start Coding Now

For Loop in Java - Syntax, Examples & Best Practices

Learn how to use for loops in Java. Complete guide with syntax, examples, nested loops, and common use cases.

Introduction

The for loop is one of the most commonly used loops in Java. It's perfect when you know how many times you want to repeat a block of code.

Basic Syntax

for (initialization; condition; update) {
    // code to be executed
}

Simple Examples

Print Numbers 1 to 10

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

Sum of First N Numbers

public class SumExample {
    public static void main(String[] args) {
        int n = 100;
        int sum = 0;
        
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        
        System.out.println("Sum of 1 to " + n + " = " + sum);
    }
}

Iterate Over Array

public class ArrayLoop {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Enhanced For Loop (For-Each)

Java provides an enhanced for loop for iterating over arrays and collections:

public class ForEachExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
        
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Nested For Loops

public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            for (int j = 1; j <= 10; j++) {
                System.out.print(i * j + "\t");
            }
            System.out.println();
        }
    }
}

Summary

  • For loops repeat code a specific number of times
  • Use enhanced for loop for arrays and collections
  • Nested loops are useful for 2D operations
  • Always ensure the loop will eventually terminate

Frequently Asked Questions

What is a for loop in Java?

A for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. It consists of initialization, condition, and update expressions.

When should I use a for loop vs while loop?

Use a for loop when you know the number of iterations beforehand. Use a while loop when the number of iterations depends on a condition that may change during execution.