Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Master Java For Loops: Syntax, Examples, and Best Practices

Master Java For Loops

This tutorial explains how to use the for loop in Java, with clear examples, detailed step‑by‑step explanations, and best‑practice guidelines.

Loops let you execute a block of code repeatedly. Instead of writing the same statement dozens of times, a loop automates the repetition, saving effort and reducing errors.

Java offers three primary loop constructs:

This article focuses on the for loop. You’ll find tutorials on the other two loop types elsewhere on our site.


Java For Loop

The for loop is ideal for situations where the number of iterations is known beforehand. Its syntax mirrors the classic C‑style loop:

for (initialExpression; testExpression; updateExpression) {
    // loop body
}

Explanation of each component:

  1. initialExpression – initializes variables and runs once.
  2. testExpression – evaluated before each iteration; if true, the loop body executes.
  3. updateExpression – executed after each iteration, typically to modify the loop counter.
  4. The loop repeats until testExpression evaluates to false.

For more on logical operators used in testExpression, see the Java relational and logical operators guide.


Example 1: Print a Message Five Times

class Main {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; ++i) {
            System.out.println("Java is fun");
        }
    }
}

Output

Java is fun
Java is fun
Java is fun
Java is fun
Java is fun

Iteration breakdown:

IterationVariablesCondition (i <= n)Action
1sti = 1
n = 5
trueJava is fun printed; i becomes 2.
2ndi = 2
n = 5
trueJava is fun printed; i becomes 3.
3rdi = 3
n = 5
trueJava is fun printed; i becomes 4.
4thi = 4
n = 5
trueJava is fun printed; i becomes 5.
5thi = 5
n = 5
trueJava is fun printed; i becomes 6.
6thi = 6
n = 5
falseLoop terminates.

Example 2: Print Numbers 1 to 5

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

Output

1
2
3
4
5

Iteration table mirrors the previous example, substituting the message with the current counter value.


Example 3: Sum of Natural Numbers 1 to 1000

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

Output

Sum = 500500

The loop adds each integer from 1 to 1000 to sum. An alternative descending form yields the same result:

class Main {
    public static void main(String[] args) {
        int sum = 0;
        int n = 1000;
        for (int i = n; i >= 1; --i) {
            sum += i;
        }
        System.out.println("Sum = " + sum);
    }
}

Java For‑Each Loop

For iterating over arrays or collections, the for‑each syntax is concise and less error‑prone:

class Main {
    public static void main(String[] args) {
        int[] numbers = {3, 7, 5, -5};
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output

3
7
5
-5

Each loop iteration assigns the next array element to number, eliminating the need for index management.

Learn more about the Java for‑each loop.


Java Infinite For Loop

An infinite loop occurs when the test expression never becomes false. Though generally avoided, it demonstrates loop control:

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

Because i starts at 1 and is decremented while the condition checks for <=10, the condition stays true indefinitely, printing "Hello" until the JVM runs out of memory.

Java

  1. Mastering C# For Loops: Syntax, Flow, and Practical Examples
  2. Master C++ For Loops: A Step-by-Step Guide
  3. Mastering the C for Loop: Syntax, Mechanics, and Practical Examples
  4. Mastering the Java Enhanced For Loop: Syntax, Examples, and Best Practices
  5. Mastering Java While & Do‑While Loops: Step‑by‑Step Tutorial
  6. Java Continue Statement – Mastering Loop Control with Examples
  7. Java For‑Each Loop: Simplifying Array Iteration Without Counters
  8. Java Program to Identify Armstrong Numbers Using For Loop
  9. Java Palindrome Number Checker: Algorithms Using While and For Loops
  10. Mastering For Loops in Verilog: Build Reusable Hardware Logic