Java for Loop & Core Loop Mechanics

โ˜• Java 21+ LTS ๐ŸŸข Chapter 19 of 47 ๐Ÿ“‚ Phase 5: Loops & Control Flow ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter:

Why Loops are Used (DRY Principle) ยท 3 Pillars (Initialization, Condition, Update) ยท for Loop Lifecycle ยท Infinite Loops ยท Sum of Numbers ยท Multiplication Table

Mastering repetitive execution and iteration in Java: understanding why loops are foundational to software engineering, the 3 pillars of loop mechanics (initialization, boolean condition, and step update), standard for loop syntax, avoiding accidental infinite loops, and building mathematical accumulation algorithms.

1. Why are Loops Used? (The DRY Principle)

In computer programming, you frequently need to repeat an action multiple times:
- Printing numbers from 1 to 100.
- Processing 10,000 customer records from a database.
- Calculating monthly compounding interest over 30 years.

Without loops, printing 5 numbers requires writing 5 separate lines of code. Printing 1,000 numbers would require 1,000 lines!

Loops allow you to write a block of code once and instruct the CPU to execute it repeatedly as long as a specified condition remains true. This enforces the fundamental engineering principle of DRY (Don't Repeat Yourself).

+-----------------------+
                     | 1. INITIALIZATION     | (int i = 1)
                     +-----------------------+
                                 |
                                 v
               +------------> < 2. CONDITION? > (i <= 5)
               |                     |
               |              (Yes)  |  (No)
               |                     v    +------------> [ Exit Loop ]
               |           +-------------------+
               |           | 3. LOOP BODY      | (Execute statements)
               |           +-------------------+
               |                     |
               |                     v
               |           +-------------------+
               +-----------| 4. UPDATE / STEP  | (i++)
                           +-------------------+

2. The 3 Pillars of Every Loop

Every loop in Java relies on three essential control components:

1. Initialization: Sets the starting point (e.g. int number = 1). Executes only once when the loop begins.
2. Condition: A boolean expression evaluated before each iteration (e.g. number <= 5). If true, the body executes; if false, the loop terminates.
3. Update (Increment / Decrement): Modifies the loop counter after each iteration (e.g. number++), moving the counter toward the termination condition to prevent infinite loops.

3. The Standard `for` Loop Syntax

The for loop combines all three control pillars into one concise, elegant header:

for (initialization; condition; update) {
    // Code executed repeatedly
}

Execution Flow Step-by-Step:

1. Step 1: initialization executes once. 2. Step 2: condition is evaluated. If false, loop ends immediately. 3. Step 3: The code inside the loop body {} executes. 4. Step 4: update step executes (e.g. i++). 5. Step 5: Jumps back to Step 2 and repeats!

4. Infinite Loops & How to Avoid Them

An Infinite Loop occurs when the loop condition never becomes false, causing the program to run forever until memory or CPU resources are exhausted:

// Accidental Infinite Loop: counter is never incremented!
for (int i = 1; i <= 5; /* missing i++ */) {
    System.out.println(i);
}

// Deliberate Infinite Loop (Common in game loops & server listeners):
for (;;) {
// Runs indefinitely until break is called
}

Beginner Example & Code Anatomy

โ˜• Main.java โ€” Chapter 19 Core Example
public class Main {
    public static void main(String[] args) {
        System.out.println("=== 1. Basic Counting Loop (1 to 5) ===");
        // The Canonical Beginner For Loop
        for (int number = 1; number <= 5; number++) {
            System.out.println("Current Number: " + number);
        }

        System.out.println("
=== 2. Mathematical Multiplication Table (Table of 7) ===");
        int multiplier = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.printf("%d x %2d = %2d%n", multiplier, i, (multiplier * i));
        }

        System.out.println("
=== 3. Sum of First 100 Natural Numbers ===");
        int totalSum = 0;
        for (int n = 1; n <= 100; n++) {
            totalSum += n; // Accumulator
        }
        System.out.println("Sum of numbers from 1 to 100 = " + totalSum);
    }
}
๐Ÿ’ป Program Console Output
=== 1. Basic Counting Loop (1 to 5) === Current Number: 1 Current Number: 2 Current Number: 3 Current Number: 4 Current Number: 5 === 2. Mathematical Multiplication Table (Table of 7) === 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 === 3. Sum of First 100 Natural Numbers === Sum of numbers from 1 to 100 = 5050

๐Ÿ” Line-by-Line Code Explanation

for (int number = 1; number <= 5; number++)

Initializes number = 1; tests if number <= 5 before each run; increments number by 1 after each run.

printf("%d x %2d = %2d%n", multiplier, i, ...)

Prints aligned multiplication table rows using %2d for clean 2-digit column width.

totalSum += n;

Accumulator pattern adding the current loop counter n into the cumulative totalSum variable.

Practical Real-World Example

โ˜• PracticalApplication.java โ€” Industry Implementation
public class MonthlySavingsInvestmentPlan {
    public static void main(String[] args) {
        double monthlyDeposit = 5000.00;
        double annualReturnRate = 0.12; // 12% annual interest
        double monthlyRate = annualReturnRate / 12;
        int totalMonths = 12;

        double accumulatedCorpus = 0;

        System.out.println("=== 1-Year Recurring Deposit Growth Schedule ===");
        System.out.printf("%-8s %-15s %-18s%n", "MONTH", "DEPOSIT (โ‚น)", "TOTAL BALANCE (โ‚น)");
        System.out.println("----------------------------------------------");

        for (int month = 1; month <= totalMonths; month++) {
            // Deposit funds and add monthly compounding interest
            accumulatedCorpus = (accumulatedCorpus + monthlyDeposit) * (1 + monthlyRate);
            System.out.printf("Month %-2d  โ‚น%,-13.2f โ‚น%,-15.2f%n", month, monthlyDeposit, accumulatedCorpus);
        }

        System.out.println("----------------------------------------------");
        System.out.printf("Total Capital Invested : โ‚น%,.2f%n", (monthlyDeposit * totalMonths));
        System.out.printf("Final Maturity Corpus  : โ‚น%,.2f%n", accumulatedCorpus);
    }
}
๐Ÿ’ป Practical Console Output
=== 1-Year Recurring Deposit Growth Schedule === MONTH DEPOSIT (โ‚น) TOTAL BALANCE (โ‚น) ---------------------------------------------- Month 1 โ‚น5,000.00 โ‚น5,050.00 Month 2 โ‚น5,000.00 โ‚น10,150.50 Month 3 โ‚น5,000.00 โ‚น15,302.01 Month 4 โ‚น5,000.00 โ‚น20,505.03 Month 5 โ‚น5,000.00 โ‚น25,760.08 Month 6 โ‚น5,000.00 โ‚น31,067.68 Month 7 โ‚น5,000.00 โ‚น36,428.35 Month 8 โ‚น5,000.00 โ‚น41,842.64 Month 9 โ‚น5,000.00 โ‚น47,311.06 Month 10 โ‚น5,000.00 โ‚น52,834.17 Month 11 โ‚น5,000.00 โ‚น58,412.52 Month 12 โ‚น5,000.00 โ‚น64,046.64 ---------------------------------------------- Total Capital Invested : โ‚น60,000.00 Final Maturity Corpus : โ‚น64,046.64
โš ๏ธ Common Mistakes & Professional Best Practices
  • Accidentally placing a semicolon after for(): Writing "for (int i=0; i<5; i++); { ... }" terminates the loop immediately and executes the block only once with i out of scope.
  • Off-by-one errors (< vs <=): "for (int i=1; i<10; i++)" runs 9 times (1 to 9). Use "<= 10" if you want 10 iterations.
  • Modifying loop variable inside loop body: Changing "i" inside the body while it also updates in the header causes unpredictable skipping or infinite loops.
๐ŸŽฏ Hands-on Coding Challenge

Test your understanding by writing the code directly in your editor or running in our online Java compiler:

โ˜• Challenge.java
// Coding Challenge:
// Write a program to compute the Factorial of a number (N = 6).
// Factorial of 6 (6!) = 6 * 5 * 4 * 3 * 2 * 1 = 720.
// Print: "Factorial of 6 = 720"

public class Main {
    public static void main(String[] args) {
        int n = 6;
        long factorial = 1;
        // TODO: Use a for loop to compute factorial
        
    }
}

๐Ÿ’ก Frequently Asked Questions & Interview Insights

โ“ Can a for loop declare multiple variables in the initialization clause?

Yes! You can declare multiple variables of the SAME type separated by commas: "for (int i = 0, j = 10; i < j; i++, j--) { ... }".

โ“ What is the scope of the variable declared in "for (int i = 0; ...)"?

The variable "i" is local to the for loop block. Attempting to access "i" after the closing brace } will trigger a "cannot find symbol" compile error.

โ“ Can we decrement in a for loop?

Yes! Countdown loops use decrement operators: "for (int count = 10; count >= 1; count--) { System.out.println(count); }".

๐Ÿš€ Quick Chapter Recap

  • Loops automate repetitive tasks adhering to the DRY (Don't Repeat Yourself) principle.
  • The for loop brings initialization, condition, and update into one header.
  • Always verify that the update step moves the counter toward the terminating condition to avoid infinite loops.
  • The accumulator pattern (sum += n) calculates running totals across iterations.
โ† Prev: 18. Modern Switch & Pitfalls Next: 20. while & do-while โ†’
OC
Curated by Our Compiler Java Technical Editorial Team
Published for 2026 Academic & Enterprise Reference ยท 100% Free & Open Access