ā˜• Java

Java For Loop — Syntax, Flow, Examples & Best Practices

Everything you need to know about Java For Loop — syntax, flow diagram, entry-controlled behavior, difference from while loop, enhanced for loop, array traversal, nested for loops, break, continue, anti-patterns, and real-world production code examples.

šŸ“…

Last Updated

March 2026

ā±ļø

Read Time

20 min

šŸŽÆ

Level

Beginner to Intermediate

šŸ·ļø

Chapter

6 of 35

What is a For Loop in Java?

A for loop in Java is an entry-controlled loop — it checks a boolean condition before executing the loop body. If the condition is false on the very first check, the body never executes. The for loop is the most commonly used loop in Java because it keeps all loop control information — initialization, condition, and update — in one compact header, making it highly readable and predictable.

Java provides three loop types: for (best when iteration count is known), while (condition checked before body — best for unknown count), and do-while (body executes first — best for at-least-once scenarios). The for loop shines when you know exactly how many times to iterate — traversing an array, printing a multiplication table, iterating over a range of numbers, or processing a fixed-size collection.

Java 5 introduced the enhanced for loop (also called for-each), which further simplifies iterating over arrays and collections by eliminating the index variable entirely. Both forms are covered in depth in this guide — along with nested loops, labeled break/continue, infinite for loops, and production-grade usage patterns.

For Loop — Syntax & Execution Flow

The for loop header has three parts separated by semicolons: initialization, condition, and update. Each part is optional — you can omit any or all of them — but both semicolons are always required. The body follows in curly braces.

šŸ“‹
For Loop Syntax

for (initialization; condition; update) { // body — executes while condition is true } Three header parts: (1) Initialization — runs ONCE before the loop starts. Typically declares and sets the loop variable: int i = 0. (2) Condition — a boolean expression checked BEFORE each iteration. If false, loop exits. If omitted, treated as always true (infinite loop). (3) Update — runs AFTER each iteration body. Typically increments or decrements: i++, i--, i+=2. Any or all parts can be omitted, but both semicolons (;;) are always required. No semicolon after the closing parenthesis — unlike do-while.

šŸ”„
Execution Flow — Step by Step

Step 1: Execute initialization (runs once only — at the very start). Step 2: Evaluate the condition. Step 3: If condition is FALSE — exit the loop; execute next statement after the loop. Step 4: If condition is TRUE — execute the loop body. Step 5: Execute the update statement. Step 6: Go back to Step 2. Key insight: initialization runs exactly once. The condition is checked before every iteration — including the very first. If condition is false from the start, the body never executes (0 iterations). This is the entry-controlled nature of the for loop.

āš–ļø
For Loop vs While — The Structural Difference

for: initialization; condition; update are all in the header — compact and self-contained. Best when iteration count is known. while: initialization is before the loop, condition is in the header, update is inside the body — more spread out. Best when iteration count is unknown or condition is event-driven. The for loop is syntactic sugar for a while loop: for(int i=0; i<n; i++){body} is exactly equivalent to: int i=0; while(i<n){body; i++;}. Choose for loop when the iteration count or range is evident from the loop header itself — it communicates intent more clearly to readers.

ā˜• JavaForLoopSyntax.java
public class ForLoopSyntax {
    public static void main(String[] args) {

        // āœ… Basic for loop — print 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
        // Output: Count: 1 through Count: 5
        // Note: i is NOT accessible here — scoped inside the for header

        // āœ… Decrement loop — countdown from 5
        for (int i = 5; i >= 1; i--) {
            System.out.print(i + " "); // 5 4 3 2 1
        }
        System.out.println();

        // āœ… Step of 2 — even numbers
        System.out.print("Even: ");
        for (int i = 2; i <= 20; i += 2) {
            System.out.print(i + " "); // 2 4 6 8 10 12 14 16 18 20
        }
        System.out.println();

        // āœ… KEY DEMO: condition FALSE from start — body NEVER runs
        System.out.print("Never prints: ");
        for (int i = 10; i < 5; i++) {
            System.out.print(i); // This never executes
        }
        System.out.println("(nothing)");

        // āœ… Variable declared BEFORE loop — accessible outside
        int j;
        for (j = 0; j < 3; j++) {
            System.out.print(j + " "); // 0 1 2
        }
        System.out.println("j after loop: " + j); // j = 3 — accessible!

        // āœ… Multiple variables in initialization and update
        for (int a = 0, b = 10; a < b; a++, b--) {
            System.out.print("(" + a + "," + b + ") "); // (0,10) (1,9) (2,8) (3,7) (4,6)
        }
        System.out.println();

        // āœ… Sum of numbers 1 to 100
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("Sum 1 to 100 = " + sum); // 5050

        // āœ… Omitting update — update inside body
        for (int i = 1; i <= 5; ) {
            System.out.print(i + " ");
            i++;  // Update inside body
        }
        System.out.println();
    }
}

For Loop Examples — Common Patterns

These examples cover the most frequently used for loop patterns in Java — from number processing and series generation to character printing and accumulator patterns. Each demonstrates why the for loop is the natural choice for known-count iteration.

ā˜• JavaForLoopExamples.java
public class ForLoopExamples {
    public static void main(String[] args) {

        // āœ… Example 1: Multiplication table
        int table = 7;
        System.out.println("--- Table of " + table + " ---");
        for (int i = 1; i <= 10; i++) {
            System.out.printf("%d x %2d = %2d%n", table, i, table * i);
        }

        // āœ… Example 2: Factorial
        int n = 6;
        long factorial = 1;
        for (int i = 2; i <= n; i++) {
            factorial *= i;
        }
        System.out.println(n + "! = " + factorial); // 720

        // āœ… Example 3: Check prime number
        int num = 29;
        boolean isPrime = num > 1;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }
        System.out.println(num + " is prime: " + isPrime); // true

        // āœ… Example 4: Fibonacci series up to n terms
        int terms = 10;
        int a = 0, b = 1;
        System.out.print("Fibonacci: ");
        for (int i = 1; i <= terms; i++) {
            System.out.print(a + " ");
            int temp = a + b;
            a = b;
            b = temp;
        }
        System.out.println();
        // Output: 0 1 1 2 3 5 8 13 21 34

        // āœ… Example 5: Sum of even numbers 1 to 50
        int evenSum = 0;
        for (int i = 2; i <= 50; i += 2) {
            evenSum += i;
        }
        System.out.println("Sum of even 1-50: " + evenSum); // 650

        // āœ… Example 6: Reverse a string using for loop
        String original = "TechSustainify";
        StringBuilder reversed = new StringBuilder();
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed.append(original.charAt(i));
        }
        System.out.println("Reversed: " + reversed); // yfiniatsuShceT

        // āœ… Example 7: Count vowels in a string
        String text = "Java Programming Language";
        int vowelCount = 0;
        String vowels = "aeiouAEIOU";
        for (int i = 0; i < text.length(); i++) {
            if (vowels.indexOf(text.charAt(i)) != -1) {
                vowelCount++;
            }
        }
        System.out.println("Vowels in '" + text + "': " + vowelCount); // 8

        // āœ… Example 8: Power of a number without Math.pow
        int base = 3, exponent = 5;
        long result = 1;
        for (int i = 1; i <= exponent; i++) {
            result *= base;
        }
        System.out.println(base + "^" + exponent + " = " + result); // 243

        // āœ… Example 9: Print all prime numbers from 1 to 50
        System.out.print("Primes 1-50: ");
        for (int i = 2; i <= 50; i++) {
            boolean prime = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) { prime = false; break; }
            }
            if (prime) System.out.print(i + " ");
        }
        System.out.println();
        // Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

        // āœ… Example 10: GCD of two numbers using for loop
        int x = 48, y = 36;
        int gcd = 1;
        for (int i = 1; i <= Math.min(x, y); i++) {
            if (x % i == 0 && y % i == 0) {
                gcd = i;
            }
        }
        System.out.println("GCD(" + x + ", " + y + ") = " + gcd); // 12
    }
}

For Loop vs While Loop — Key Differences

Both for and while are entry-controlled loops — they check the condition before executing the body. The difference is structural and semantic: the for loop bundles initialization, condition, and update in one header; the while loop separates them. The choice communicates intent to every future reader of your code.

Featurefor Loopwhile Loop
Loop typeEntry-controlledEntry-controlled
Condition checkedBEFORE body — every iterationBEFORE body — every iteration
Minimum executions0 — body may never run if condition false0 — body may never run if condition false
Initialization locationInside loop header — self-containedBefore the loop — external
Update locationThird part of header — always runs after bodyInside body — can be skipped with continue
Semicolon requiredNo semicolon after closing parenthesisNo semicolon after closing parenthesis
Variable scopeLoop variable can be scoped inside headerLoop variable always external — wider scope
Best forKnown iteration count, array traversal, index loopsUnknown count, event-driven, reading until EOF
Readability (known count)Excellent — all info in one lineVerbose — info spread across multiple lines
Readability (unknown count)Awkward — empty parts look oddNatural — while(condition) is clear
Enhanced formEnhanced for / for-each availableNo enhanced form
Common use casesArray iteration, patterns, fixed range, matrixPolling, file reading, game loops, retry
ā˜• JavaForLoopVsWhile.java
public class ForLoopVsWhile {
    public static void main(String[] args) {

        // āœ… Known count — for loop is cleaner
        System.out.print("for (known count): ");
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " "); // 1 2 3 4 5
        }
        System.out.println();

        // Same with while — more verbose
        System.out.print("while (known count): ");
        int i = 1;          // Initialization before loop
        while (i <= 5) {
            System.out.print(i + " "); // 1 2 3 4 5
            i++;            // Update inside body
        }
        System.out.println();

        // āœ… Unknown count — while is more natural
        // Read digits of a number until none remain
        int number = 98765;
        System.out.print("Digits (while, natural): ");
        while (number > 0) {
            System.out.print(number % 10 + " ");
            number /= 10;
        }
        System.out.println();

        // Same with for — awkward empty init section
        int num2 = 98765;
        System.out.print("Digits (for, awkward): ");
        for (; num2 > 0; num2 /= 10) {
            System.out.print(num2 % 10 + " ");
        }
        System.out.println();

        // āœ… Variable scope difference — important!
        for (int x = 0; x < 3; x++) { }
        // System.out.println(x); // āŒ COMPILE ERROR — x not accessible here

        int y = 0;
        while (y < 3) { y++; }
        System.out.println("y after while: " + y); // āœ… y = 3 — accessible

        // āœ… For loop with continue — update still runs (unlike while!)
        System.out.print("for continue: ");
        for (int k = 1; k <= 5; k++) {
            if (k == 3) continue; // Skips body but k++ in header STILL runs
            System.out.print(k + " "); // 1 2 4 5 — 3 skipped, no infinite loop
        }
        System.out.println();

        // while with continue — must update BEFORE continue or infinite loop!
        System.out.print("while continue (safe): ");
        int m = 0;
        while (m < 5) {
            m++;            // Update BEFORE continue — critical!
            if (m == 3) continue;
            System.out.print(m + " "); // 1 2 4 5
        }
        System.out.println();
    }
}

Enhanced For Loop (For-Each) — Clean Collection Iteration

The enhanced for loop (introduced in Java 5) provides a concise, readable way to iterate over arrays and any class that implements Iterable (List, Set, Map values, etc.). It eliminates index management entirely — no initialization, no condition, no update. Just element by element, from first to last.

āœ…
When to Use Enhanced For Loop

Use enhanced for (for-each) when: (1) You need every element in order from first to last. (2) You do not need the index of each element. (3) You do not need to modify the array/collection during iteration. (4) You want clean, readable code that communicates 'process each element.' Perfect for: printing all elements, summing values, finding max/min, filtering, checking conditions across all elements. The enhanced for loop is the preferred idiom in modern Java code for array and collection traversal.

🚫
When NOT to Use Enhanced For Loop

Do NOT use enhanced for when: (1) You need the index — use traditional for(int i=0; i<arr.length; i++). (2) You need to modify array elements — the loop variable is a copy (for primitives) or reference copy (for objects), not the actual slot. (3) You need to iterate in reverse. (4) You need to skip elements by index. (5) You need to iterate two arrays in parallel (two indices). (6) You need to remove elements from a List while iterating — use Iterator.remove() or removeIf(). In all these cases, fall back to the traditional for loop or Iterator.

šŸ’”
Enhanced For Loop — Read-Only Caveat

For primitive arrays (int[], double[]), the loop variable is a copy of each value. Changing it does NOT change the array: for(int x : arr) { x = 0; } — the array is unchanged. For object arrays (String[], MyClass[]), the loop variable is a reference copy — you can call mutating methods on the object, but reassigning the variable (element = new MyClass()) does NOT affect the array. To truly modify array elements, use a traditional for loop with the index: arr[i] = newValue.

ā˜• JavaEnhancedForLoop.java
import java.util.*;

public class EnhancedForLoop {
    public static void main(String[] args) {

        // āœ… Enhanced for with int array
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.print("Elements: ");
        for (int num : numbers) {
            System.out.print(num + " "); // 10 20 30 40 50
        }
        System.out.println();

        // āœ… Sum using enhanced for
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum: " + sum); // 150

        // āœ… Enhanced for with String array
        String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }

        // āœ… Enhanced for with ArrayList
        List<String> cities = new ArrayList<>(List.of("Delhi", "Mumbai", "Bangalore", "Hyderabad"));
        System.out.println("Cities:");
        for (String city : cities) {
            System.out.println("  - " + city);
        }

        // āœ… Enhanced for with 2D array — outer loop
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println("Matrix:");
        for (int[] row : matrix) {       // Each row is an int[]
            for (int val : row) {         // Each value in the row
                System.out.printf("%3d", val);
            }
            System.out.println();
        }

        // āœ… Find max using enhanced for
        int[] scores = {85, 92, 78, 96, 88};
        int max = scores[0];
        for (int score : scores) {
            if (score > max) max = score;
        }
        System.out.println("Max score: " + max); // 96

        // āŒ Enhanced for does NOT modify primitive array
        int[] arr = {1, 2, 3};
        for (int x : arr) {
            x = x * 10; // Modifies copy — arr is UNCHANGED
        }
        System.out.println("arr[0] after attempt: " + arr[0]); // Still 1

        // āœ… Correct way to modify — use traditional for with index
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 10; // Modifies actual array slot
        }
        System.out.println("arr[0] after fix: " + arr[0]); // 10

        // āœ… Enhanced for with Set (unordered — no index guarantee)
        Set<Integer> primeSet = new HashSet<>(Set.of(2, 3, 5, 7, 11));
        System.out.print("Primes: ");
        for (int p : primeSet) {
            System.out.print(p + " "); // Order not guaranteed for HashSet
        }
        System.out.println();

        // āœ… Enhanced for with Map.entrySet()
        Map<String, Integer> scores2 = new LinkedHashMap<>();
        scores2.put("Alice", 95);
        scores2.put("Bob", 87);
        scores2.put("Carol", 92);
        for (Map.Entry<String, Integer> entry : scores2.entrySet()) {
            System.out.printf("%s: %d%n", entry.getKey(), entry.getValue());
        }
    }
}

For Loop with Arrays — The Essential Pattern

Arrays and for loops are inseparable in Java. The for loop is the primary tool for array traversal, searching, sorting, filling, copying, and manipulation. Understanding how to use for loops with single-dimensional, multi-dimensional, and jagged arrays is a core Java skill.

ā˜• JavaForLoopArrays.java
import java.util.Arrays;

public class ForLoopArrays {
    public static void main(String[] args) {

        // āœ… Fill array with squares
        int[] squares = new int[10];
        for (int i = 0; i < squares.length; i++) {
            squares[i] = (i + 1) * (i + 1);
        }
        System.out.println("Squares: " + Arrays.toString(squares));
        // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

        // āœ… Linear search
        int[] data = {34, 7, 23, 32, 5, 62};
        int target = 23;
        int foundAt = -1;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == target) {
                foundAt = i;
                break;
            }
        }
        System.out.println(target + " found at index: " + foundAt); // 2

        // āœ… Reverse array in-place
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        System.out.println("Reversed: " + Arrays.toString(arr)); // [5, 4, 3, 2, 1]

        // āœ… Bubble sort using nested for loops
        int[] toSort = {64, 34, 25, 12, 22, 11, 90};
        int n = toSort.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (toSort[j] > toSort[j + 1]) {
                    int temp = toSort[j];
                    toSort[j] = toSort[j + 1];
                    toSort[j + 1] = temp;
                }
            }
        }
        System.out.println("Sorted: " + Arrays.toString(toSort));
        // [11, 12, 22, 25, 34, 64, 90]

        // āœ… 2D array traversal
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println("Matrix diagonal sum:");
        int diagSum = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.printf("%3d", matrix[i][j]);
                if (i == j) diagSum += matrix[i][j]; // Main diagonal
            }
            System.out.println();
        }
        System.out.println("Diagonal sum: " + diagSum); // 15

        // āœ… Jagged array (different row lengths)
        int[][] jagged = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}};
        System.out.println("Jagged array:");
        for (int i = 0; i < jagged.length; i++) {
            for (int j = 0; j < jagged[i].length; j++) { // jagged[i].length varies
                System.out.print(jagged[i][j] + " ");
            }
            System.out.println();
        }
        // 1
        // 2 3
        // 4 5 6
        // 7 8 9 10
    }
}

Break and Continue in For Loop

break and continue are loop control statements that alter the normal flow of a for loop. break exits the loop entirely. continue skips the current iteration's remaining body and proceeds to the update step, then condition check. A critical advantage of the for loop: the update expression in the header always executes after continue — unlike in a while loop where forgetting to update before continue causes an infinite loop.

šŸ›‘
break in For Loop

break immediately exits the for loop — the update and condition are not executed for that iteration. Execution resumes at the statement after the closing brace of the for loop. Use break for: early exit on target found (linear search), stopping when a condition is met (first invalid element), exiting infinite for(;;) loops, and limiting iterations in retry patterns. Labeled break (break label;) exits a specified outer loop when dealing with nested loops — used when inner loop needs to break out of multiple levels.

ā­ļø
continue in For Loop

continue skips the remaining body of the current iteration and jumps to the update expression (i++ etc.), then to the condition check. This is a key advantage over while loops — in a for loop, continue can never accidentally skip the update because the update is in the header, not the body. Use continue for: skipping specific values (null checks, even/odd filtering), ignoring invalid data, processing only elements that meet a condition, and simplifying nested if-else inside loops by using guard-clause style with continue.

šŸ·ļø
Labeled break and continue

Java supports labeled break and continue for nested loops. A label is an identifier followed by a colon placed before a loop: outer: for(...) { inner: for(...) { break outer; } }. break outer exits the outer loop entirely from inside the inner loop. continue outer skips to the outer loop's next iteration. Labels are rarely needed — most use cases can be solved by extracting to a method and using return. But they are valid Java and occasionally the cleanest solution for nested loop control flow, especially in matrix/grid traversal algorithms.

ā˜• JavaBreakContinueForLoop.java
public class BreakContinueForLoop {
    public static void main(String[] args) {

        // āœ… break — exit on first match (linear search)
        System.out.println("--- break in for loop ---");
        int[] arr = {3, 7, 1, 9, 4, 6, 2};
        int target = 9;
        int foundIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                foundIndex = i;
                break;  // Stop searching once found
            }
        }
        System.out.println(target + " found at index: " + foundIndex); // 3

        // āœ… continue — skip specific values (print odd numbers only)
        System.out.println("\n--- continue in for loop ---");
        System.out.print("Odd numbers 1-10: ");
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) continue; // Skip even — i++ in header ALWAYS runs
            System.out.print(i + " "); // 1 3 5 7 9
        }
        System.out.println();

        // āœ… continue — skip null/blank strings
        String[] names = {"Alice", null, "Bob", "", "Charlie", null, "David"};
        System.out.print("Valid names: ");
        for (String name : names) {
            if (name == null || name.isBlank()) continue;
            System.out.print(name + " ");
        }
        System.out.println();
        // Output: Alice Bob Charlie David

        // āœ… Labeled break — exit outer loop from inner
        System.out.println("\n--- labeled break ---");
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int searchVal = 5;
        int row = -1, col = -1;
        outer:                              // Label for outer loop
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == searchVal) {
                    row = i;
                    col = j;
                    break outer;            // Exit BOTH loops
                }
            }
        }
        System.out.println(searchVal + " found at [" + row + "][" + col + "]"); // [1][1]

        // āœ… Labeled continue — skip outer iteration from inner
        System.out.println("\n--- labeled continue ---");
        System.out.println("Rows without any zero:");
        outerLoop:
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0) {
                    continue outerLoop;     // Skip this entire row
                }
            }
            System.out.println("  Row " + i + ": no zeros");
        }

        // āœ… break in infinite for(;;) loop
        System.out.println("\n--- break in infinite for ---");
        int count = 0;
        for (;;) {                          // Infinite loop
            count++;
            System.out.print(count + " ");
            if (count == 5) break;          // Exit when count reaches 5
        }
        System.out.println("\nStopped at: " + count); // 5
    }
}

Nested For Loops — Patterns, Arrays & Algorithms

Nested for loops place one for loop inside another. The inner loop executes completely for every single iteration of the outer loop. Nested loops are essential for 2D array operations, pattern printing, sorting algorithms, and combinatorial problems. The total number of body executions is the product of both loops' iteration counts.

ā˜• JavaNestedForLoops.java
public class NestedForLoops {
    public static void main(String[] args) {

        // āœ… Example 1: Multiplication table grid (1-5 x 1-5)
        System.out.println("Multiplication Table:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.printf("%4d", i * j);
            }
            System.out.println();
        }
        //    1   2   3   4   5
        //    2   4   6   8  10
        //    3   6   9  12  15  etc.

        // āœ… Example 2: Right triangle star pattern
        System.out.println("\nRight Triangle:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        // *
        // * *
        // * * *
        // * * * *
        // * * * * *

        // āœ… Example 3: Inverted triangle
        System.out.println("\nInverted Triangle:");
        for (int i = 5; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        // āœ… Example 4: Number pattern — Floyd's triangle
        System.out.println("\nFloyd's Triangle:");
        int num = 1;
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.printf("%3d", num++);
            }
            System.out.println();
        }
        //   1
        //   2  3
        //   4  5  6
        //   7  8  9 10
        //  11 12 13 14 15

        // āœ… Example 5: Pyramid pattern (centered)
        System.out.println("\nPyramid:");
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int s = 1; s <= rows - i; s++) System.out.print(" "); // Spaces
            for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");  // Stars
            System.out.println();
        }
        //     *
        //    ***
        //   *****
        //  *******
        // *********

        // āœ… Example 6: Diamond pattern
        System.out.println("\nDiamond:");
        int n = 5;
        // Upper half
        for (int i = 1; i <= n; i++) {
            for (int s = n; s > i; s--) System.out.print(" ");
            for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
            System.out.println();
        }
        // Lower half
        for (int i = n - 1; i >= 1; i--) {
            for (int s = n; s > i; s--) System.out.print(" ");
            for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
            System.out.println();
        }

        // āœ… Example 7: Matrix multiplication (O(n³) — classic nested loop)
        int[][] A = {{1, 2}, {3, 4}};
        int[][] B = {{5, 6}, {7, 8}};
        int size = 2;
        int[][] C = new int[size][size];
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                for (int k = 0; k < size; k++) {
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        System.out.println("\nMatrix C[0][0]: " + C[0][0]); // 19
        System.out.println("Matrix C[1][1]: " + C[1][1]); // 50
    }
}

For Loop vs Do-While Loop — When to Use Which

The for loop and do-while loop are at opposite ends of the loop spectrum. The for loop is entry-controlled with a known count. The do-while is exit-controlled with a guaranteed first execution. Choosing between them correctly signals clear intent in your code.

Aspectfor Loopdo-while Loop
Control typeEntry-controlled — checks before bodyExit-controlled — body runs before check
Minimum executions0 — body may not run at all1 — body always runs at least once
Iteration countBest when count is knownBest when count is unknown, runs until condition
Header structureinit; condition; update — all in one lineCondition at the bottom only
Semicolon requiredNo — for(;;){} no trailing semicolonYes — while(condition); mandatory semicolon
Variable scopeCan scope variable inside headerVariable always declared externally
Enhanced formYes — for-each for arrays/collectionsNo enhanced form
Best use casesArrays, fixed ranges, patterns, algorithmsMenus, input validation, game loops, retry
If condition false initiallyBody never executes — clean behaviourBody still runs once — can be surprising
Code duplicationNone — but prime read needed for some patternsNone — body written once, always runs first
ā˜• JavaForVsDoWhile.java
public class ForVsDoWhile {
    public static void main(String[] args) {

        // āœ… For loop — best for known count (array traversal)
        int[] grades = {85, 92, 78, 96, 88};
        int total = 0;
        for (int grade : grades) {
            total += grade;
        }
        System.out.println("Average: " + (total / grades.length)); // 87
        // for-each is the natural, clearest choice here

        // āœ… Do-while — best for 'must run at least once' (menu/validation)
        // Simulated: keep prompting until valid grade is entered
        int[] simulatedInputs = {-5, 150, 88}; // Invalid, invalid, valid
        int idx = 0;
        int validGrade;
        do {
            validGrade = simulatedInputs[idx++];
            System.out.println("Entered grade: " + validGrade);
            if (validGrade < 0 || validGrade > 100)
                System.out.println("  Invalid! Try again.");
        } while (validGrade < 0 || validGrade > 100);
        System.out.println("Valid grade accepted: " + validGrade); // 88

        // āœ… For loop for fixed game rounds — NOT do-while
        System.out.println("\nPlaying 3 rounds:");
        for (int round = 1; round <= 3; round++) {
            int score = (int)(Math.random() * 100);
            System.out.println("  Round " + round + " score: " + score);
        }
        // Known count (3 rounds) = for loop is correct choice

        // āœ… Do-while for unknown rounds — play until user stops
        String[] choices = {"Y", "Y", "N"}; // Simulated play-again choices
        int gameIdx = 0;
        int roundNum = 0;
        do {
            roundNum++;
            System.out.println("Playing round " + roundNum + "...");
            String playAgain = choices[gameIdx++];
            System.out.println("Play again? " + playAgain);
            if (playAgain.equalsIgnoreCase("N")) break;
        } while (true);
        System.out.println("Total rounds played: " + roundNum); // 3
    }
}

Infinite For Loop — for(;;)

An infinite for loop is written as for(;;) — all three header parts are omitted. With no condition, the loop runs forever. It is functionally identical to while(true) and must be exited with break, return, or by throwing an exception. The for(;;) form is a recognized Java idiom, often preferred in systems and server-side code for clarity.

ā˜• JavaInfiniteForLoop.java
import java.util.*;

public class InfiniteForLoop {
    public static void main(String[] args) {

        // āœ… Pattern 1: for(;;) as event loop (simulated)
        System.out.println("--- Event Processing Loop ---");
        Queue<String> events = new LinkedList<>(List.of("CONNECT", "REQUEST", "RESPONSE", "SHUTDOWN"));
        for (;;) {
            if (events.isEmpty()) {
                System.out.println("No more events. Exiting.");
                break;
            }
            String event = events.poll();
            System.out.println("Processing: " + event);
            if ("SHUTDOWN".equals(event)) {
                System.out.println("Shutdown received. Stopping loop.");
                break;
            }
        }

        // āœ… Pattern 2: Retry with max attempts using for(;;)
        System.out.println("\n--- Retry Loop ---");
        int maxRetries = 4;
        int attempt = 0;
        for (;;) {
            attempt++;
            System.out.println("Attempt " + attempt + ": connecting...");
            boolean connected = attempt == 3; // Simulated: succeeds on 3rd try
            if (connected) {
                System.out.println("āœ… Connected on attempt " + attempt);
                break;
            }
            if (attempt >= maxRetries) {
                System.out.println("āŒ Failed after " + maxRetries + " attempts.");
                break;
            }
            System.out.println("  Retrying in " + (attempt * 500) + "ms...");
        }

        // āœ… Pattern 3: Number guessing game frame (simulated input)
        System.out.println("\n--- Guessing Game ---");
        int secret = 42;
        int[] guesses = {10, 60, 42}; // Simulated guesses
        int gi = 0;
        for (;;) {
            int guess = guesses[gi++];
            System.out.println("Guess: " + guess);
            if (guess == secret) {
                System.out.println("šŸŽ‰ Correct in " + gi + " guesses!");
                break;
            } else if (guess < secret) {
                System.out.println("  Too low.");
            } else {
                System.out.println("  Too high.");
            }
        }

        // āœ… for(;;) vs while(true) — identical bytecode, different style
        // Both are accepted Java idioms.
        // for(;;) is more common in systems/server code.
        // while(true) reads more naturally as 'run forever'.
        // Choose based on your team's style guide.
        int counter = 0;
        for (;;) {
            if (++counter >= 3) break;
            System.out.println("for(;;) counter: " + counter);
        }
    }
}

Common Mistakes & Pitfalls — Bugs That Fool Everyone

These are the most common for loop mistakes in Java — off-by-one errors, semicolon after the header, infinite loops from missing updates, and subtle scoping issues that trip up beginners and occasionally experienced developers too.

ā˜• JavaForLoopMistakes.java
// āŒ MISTAKE 1: Semicolon after for header — empty body!
// for (int i = 0; i < 5; i++);   // ← This semicolon creates an empty body!
// {
//     System.out.println(i);       // This runs ONCE after the loop — outside it
// }
// The semicolon terminates the for statement; the block {} is a separate statement.
// āœ… Fix: no semicolon after the for header
for (int i = 0; i < 5; i++) {
    System.out.println(i);  // āœ… Correct
}

// āŒ MISTAKE 2: Off-by-one — using < vs <=
int[] arr = {10, 20, 30, 40, 50};
// for (int i = 0; i <= arr.length; i++) {  // āŒ ArrayIndexOutOfBoundsException at i=5
//     System.out.println(arr[i]);
// }
// āœ… Fix: use < arr.length (not <=)
for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");  // āœ…
}
System.out.println();

// āŒ MISTAKE 3: Modifying loop variable inside body (unexpected behavior)
// for (int i = 0; i < 5; i++) {
//     System.out.println(i);
//     i++;  // āŒ i incremented TWICE per iteration — prints only 0, 2, 4
// }
// āœ… Fix: update ONLY in the header unless intentional
for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");  // 0 1 2 3 4 — correct
}
System.out.println();

// āŒ MISTAKE 4: Variable scope — accessing loop variable outside loop
for (int i = 0; i < 3; i++) { }
// System.out.println(i);  // āŒ COMPILE ERROR: i not accessible here
// āœ… Fix: declare before loop if needed outside
int j;
for (j = 0; j < 3; j++) { }
System.out.println("j after loop: " + j); // āœ… j = 3

// āŒ MISTAKE 5: Float/double loop variable — precision errors
// for (double d = 0.0; d != 1.0; d += 0.1) {  // āŒ May NEVER equal exactly 1.0!
//     System.out.println(d);  // Runs forever or terminates unpredictably
// }
// āœ… Fix: use integer counter, or use < with tolerance
for (int i = 0; i <= 10; i++) {
    double d = i * 0.1;
    System.out.printf("%.1f ", d);  // 0.0 0.1 0.2 ... 1.0
}
System.out.println();

// āŒ MISTAKE 6: ConcurrentModificationException in enhanced for + List modification
java.util.List<String> list = new java.util.ArrayList<>(java.util.List.of("A","B","C"));
// for (String s : list) {
//     if (s.equals("B")) list.remove(s);  // āŒ ConcurrentModificationException!
// }
// āœ… Fix: use removeIf (Java 8+) or Iterator
list.removeIf(s -> s.equals("B"));  // āœ… Safe removal
System.out.println("List after remove: " + list); // [A, C]

// āŒ MISTAKE 7: Infinite loop from wrong condition direction
// for (int i = 0; i >= 0; i++) {  // āŒ i grows forever — infinite loop
//     System.out.println(i);
// }
// āœ… Fix: ensure condition becomes false — use i-- for countdown
for (int i = 5; i > 0; i--) {
    System.out.print(i + " ");  // 5 4 3 2 1
}
System.out.println();

Bad Practices & Anti-Patterns — What Senior Developers Reject

These anti-patterns represent common misuses of for loops in professional Java code. Each one either causes bugs, reduces readability, or makes code harder to maintain and test.

🚫
Skipping Curly Braces

Java allows a for loop with a single statement and no braces: for(int i=0; i<5; i++) System.out.println(i); — but this is dangerous and universally rejected in professional code. Adding a second statement below it while thinking it is inside the loop creates a silent logic bug (it runs only once, after the loop ends). Always use curly braces for all for loop bodies. Every major Java style guide (Google, Oracle) mandates braces. There are no exceptions to this rule in production code.

🚫
Hardcoding Magic Numbers

Writing for(int i=0; i<7; i++) or for(int i=0; i<students.length; i++) with the literal 7 as a magic number makes intent unclear and changes fragile. Define named constants: private static final int DAYS_IN_WEEK = 7; then use for(int i=0; i<DAYS_IN_WEEK; i++). For array bounds, always use arr.length — never hardcode the size. SonarQube and other static analysis tools flag magic numbers in loop conditions as code quality violations.

🚫
Using Index When Enhanced For Suffices

Writing for(int i=0; i<list.size(); i++) { process(list.get(i)); } when you do not need the index is unnecessarily verbose. The enhanced for loop for(String s : list) { process(s); } is shorter, more readable, and communicates 'process every element' without the noise of index management. Reserve the traditional indexed for loop for cases that genuinely require the index. Using it everywhere 'just in case' you need the index is an anti-pattern that clutters code.

🚫
Calling size() / length() in Every Iteration

Writing for(int i=0; i<list.size(); i++) calls list.size() on every iteration. For ArrayList this is O(1) and harmless, but for custom collections or LinkedList variants it could be O(n), making the loop O(n²). Best practice: cache the size before the loop: int size = list.size(); for(int i=0; i<size; i++). For arrays, arr.length is a field access (O(1)) so caching is optional — but for collections, always cache the size for clarity and safety.

🚫
Deeply Nested For Loops Without Extraction

Three or more levels of nested for loops create code that is nearly impossible to read, debug, and test. It is a strong signal to refactor: extract inner loops into separate methods with descriptive names (e.g. processRow, findColumn), replace O(n²) search loops with HashMap lookups, use Java Streams for filtering and transformation, or break the problem into smaller composable functions. Deep nesting also indicates O(n³) or worse complexity — always evaluate algorithmic alternatives before accepting cubic-time nested loops.

🚫
Mutating Collection While Iterating With For-Each

Adding or removing elements from a List, Set, or Map while iterating it with an enhanced for loop causes ConcurrentModificationException at runtime. This is a common but easily avoided mistake. Never modify the collection being iterated in a for-each. Instead: use list.removeIf(predicate) for removals (Java 8+), collect items to a separate list and process after the loop, use Iterator explicitly with iterator.remove() for safe removal during iteration, or use a traditional indexed for loop when mutation is required.

Real-World Production Code Examples — For Loop in Context

The following examples show idiomatic, production-grade Java for loop usage — patterns seen in real Spring Boot services, data processing pipelines, and enterprise Java codebases.

ā˜• JavaReportGenerator.java — Batch Report with For Loop
package com.techsustainify.reports;

import java.util.*;

public class ReportGenerator {

    record Student(String name, int[] marks) {}

    // āœ… Generate report for all students
    public void generateClassReport(List<Student> students) {
        if (students == null || students.isEmpty()) {
            System.out.println("No students to report.");
            return;
        }

        System.out.println("╔══════════════════════════════════════════╗");
        System.out.println("ā•‘           CLASS PERFORMANCE REPORT       ā•‘");
        System.out.println("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•");

        int classTotal = 0;
        int highestAverage = 0;
        String topper = "";

        // āœ… For-each — no index needed for student processing
        for (Student student : students) {
            int sum = 0;
            int highest = 0;
            int lowest = Integer.MAX_VALUE;

            // āœ… Traditional for — need index for subject numbering
            for (int i = 0; i < student.marks().length; i++) {
                int mark = student.marks()[i];
                sum += mark;
                if (mark > highest) highest = mark;
                if (mark < lowest) lowest = mark;
                System.out.printf("  Subject %d: %d%n", i + 1, mark);
            }

            int avg = sum / student.marks().length;
            classTotal += avg;

            if (avg > highestAverage) {
                highestAverage = avg;
                topper = student.name();
            }

            String grade = avg >= 90 ? "A+" : avg >= 80 ? "A" : avg >= 70 ? "B" : avg >= 60 ? "C" : "F";
            System.out.printf("%-15s | Avg: %3d | High: %3d | Low: %3d | Grade: %s%n",
                student.name(), avg, highest, lowest, grade);
        }

        System.out.println("Class Average: " + (classTotal / students.size()));
        System.out.println("Top Performer: " + topper + " (" + highestAverage + ")");
    }

    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Alice",   new int[]{92, 88, 95, 91, 89}),
            new Student("Bob",     new int[]{75, 82, 70, 78, 85}),
            new Student("Charlie", new int[]{60, 65, 58, 72, 68})
        );
        new ReportGenerator().generateClassReport(students);
    }
}
ā˜• JavaDataProcessor.java — CSV Validation & Transformation
package com.techsustainify.data;

import java.util.*;

public class DataProcessor {

    private static final int MAX_AGE = 120;
    private static final int MIN_AGE = 0;
    private static final int MAX_SALARY = 10_000_000;

    record Employee(String name, int age, double salary) {}

    // āœ… Validate and transform a batch of employee records
    public List<Employee> processEmployeeData(List<String[]> rawData) {
        List<Employee> validEmployees = new ArrayList<>();
        List<String> errors = new ArrayList<>();

        // āœ… Traditional for with index — need row number for error reporting
        for (int i = 0; i < rawData.size(); i++) {
            String[] row = rawData.get(i);
            int rowNum = i + 1; // 1-based for human-readable error messages

            if (row.length != 3) {
                errors.add("Row " + rowNum + ": Expected 3 columns, got " + row.length);
                continue;
            }

            String name = row[0].strip();
            if (name.isBlank()) {
                errors.add("Row " + rowNum + ": Name cannot be blank");
                continue;
            }

            int age;
            try {
                age = Integer.parseInt(row[1].strip());
            } catch (NumberFormatException e) {
                errors.add("Row " + rowNum + ": Invalid age '" + row[1] + "'");
                continue;
            }
            if (age < MIN_AGE || age > MAX_AGE) {
                errors.add("Row " + rowNum + ": Age " + age + " out of range [" + MIN_AGE + "-" + MAX_AGE + "]");
                continue;
            }

            double salary;
            try {
                salary = Double.parseDouble(row[2].strip());
            } catch (NumberFormatException e) {
                errors.add("Row " + rowNum + ": Invalid salary '" + row[2] + "'");
                continue;
            }
            if (salary < 0 || salary > MAX_SALARY) {
                errors.add("Row " + rowNum + ": Salary " + salary + " out of range");
                continue;
            }

            validEmployees.add(new Employee(name, age, salary));
        }

        // āœ… For-each for reporting — no index needed
        if (!errors.isEmpty()) {
            System.out.println("\nāš ļø Validation Errors:");
            for (String error : errors) {
                System.out.println("  " + error);
            }
        }
        System.out.println("\nāœ… Valid records: " + validEmployees.size() + "/" + rawData.size());
        return validEmployees;
    }

    public static void main(String[] args) {
        List<String[]> data = List.of(
            new String[]{"Alice", "30", "75000"},
            new String[]{"Bob", "200", "50000"},   // Invalid age
            new String[]{"", "25", "60000"},       // Blank name
            new String[]{"Charlie", "abc", "80000"}, // Invalid age format
            new String[]{"Diana", "28", "90000"}
        );
        new DataProcessor().processEmployeeData(data);
    }
}

For Loop Flow Diagram — Visualizing Execution

This flowchart shows the execution flow of the for loop — highlighting how initialization runs exactly once, the condition is checked before every iteration including the first, and the update runs after every body execution but before the next condition check.

ā–¶ StartBegin execution
Start
šŸ”§ Initializationint i = 0 — runs ONCE only
Check condition first time
šŸ” Evaluate Conditioni < n — checked BEFORE every iteration
FALSE — exit
āš™ļø Execute Loop BodyRuns only if condition is TRUE
Check for break
šŸ›‘ break encountered?Optional early exit
YES — exit immediately
ā­ļø continue encountered?Skip to update step
YES — skip to update
šŸ”„ Update Expressioni++ — runs after every iteration
Re-check condition
āœ… Exit LoopContinue with next statement

Code Execution Flow — from source to output

Java For Loop Interview Questions — Beginner to Advanced

For loop questions test your understanding of entry-controlled loops, the three-part header, variable scope, enhanced for loop limitations, and the behavior of break and continue. These appear frequently in Java interviews at all levels.

Practice Questions — Test Your For Loop Knowledge

Challenge yourself with these practice questions. Attempt each independently before reading the answer — writing and tracing code by hand significantly improves retention and interview readiness.

1. What is the output? for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; System.out.print(i + " "); }

Easy

2. What is printed after this code runs? int sum = 0; for (int i = 1; i <= 10; i++) { if (i % 3 == 0) continue; sum += i; } System.out.println(sum);

Easy

3. Write a for loop program to check whether a given number is a perfect number (sum of its proper divisors equals the number itself). Example: 28 = 1+2+4+7+14.

Medium

4. Trace the output of this code: int result = 0; for (int i = 1; i <= 5; i++) { result += i * i; if (result > 20) break; } System.out.println(result);

Medium

5. Using nested for loops, print the following pattern: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1

Medium

6. What is the output? Why? int x = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == j) break; x++; } } System.out.println(x);

Hard

7. Write a program using a for loop to find all Armstrong numbers between 1 and 1000. (An Armstrong number equals the sum of its digits each raised to the power of the number of digits — e.g., 153 = 1³+5³+3³.)

Hard

8. What is the difference in variable accessibility after these two loops? // Loop A for (int i = 0; i < 3; i++) { } // Loop B int j = 0; for (; j < 3; j++) { }

Easy

Conclusion — For Loop: The Workhorse of Java Iteration

The for loop is Java's most versatile and widely used loop. Its three-part header — initialization, condition, update — keeps all iteration control in one compact, readable line. It is the natural choice whenever you know how many times to iterate, need an index, or are traversing an array or collection by position.

Mastering the for loop means understanding not just its syntax — the two mandatory semicolons, the scoping of the loop variable, the always-safe continue behavior — but also its variants: the enhanced for loop for clean collection iteration, multiple variable headers for two-pointer patterns, labeled break/continue for nested loop control, and for(;;) for intentional infinite loops. Choosing the right loop type — for, while, or do-while — and using the right variant — traditional or enhanced — is the mark of an experienced Java developer.

ConceptKey PointWhen to Use
for loop syntaxfor(init; condition; update){} — two semicolons, no trailing semicolonAlways — standard for loop
Entry-controlledCondition checked BEFORE body — may execute 0 timesWhen body should be skipped if condition false
vs while loopfor: known count, compact; while: unknown count, flexiblefor: index/range; while: event-driven/unknown count
Enhanced for (for-each)for(Type e : array/collection) — no index, read-only for primitivesAll elements in order, no index needed
Multiple variablesfor(int i=0, j=n-1; i<j; i++, j--)Two-pointer, parallel index, converging iteration
break in for loopExits loop immediately — skips condition and updateEarly exit on target found or error condition
continue in for loopSkips body, runs update (i++), then checks conditionSkip specific values — update always safe in for
Labeled break/continuebreak outerLabel; exits named outer loopNested loop control — rarely needed; prefer method extraction
for(;;) infinite loopAll three parts omitted — runs forever until break/returnEvent loops, server loops, retry patterns
Nested for loopsInner runs fully per outer iteration — O(n²) minimumPatterns, 2D arrays, sorting — watch complexity

Your next step: Java While Loop — the other entry-controlled loop, best for unknown iteration counts, event-driven conditions, and scenarios where the for loop's structure would feel forced or unnatural. ā˜•

Frequently Asked Questions — Java For Loop