Skip to main content
Published on

For Loop in Java

Share:

Introduction

The for loop is one of the most versatile flow control structures in Java, allowing you to repeat a block of code a defined number of times. It is especially useful when we know in advance how many times we want to execute an action.

The Structure of the For Loop

Basic Syntax

The basic form of the for loop consists of three parts: initialization, condition, and increment/decrement.

for (initialization; condition; increment/decrement) {
  // block of code to be repeated
}

How Does It Work?

  1. Initialization: This part is executed once at the beginning. It is generally used to declare and initialize the control variable.
  2. Condition: Before each iteration, the condition is evaluated. If it is true, the block of code is executed. Otherwise, the loop ends.
  3. Increment/Decrement: After each iteration, this part is executed, allowing the control variable to be updated.

Practical Example

package com.caffeinealgorithm.programaremjava;

public class ForLoop {
  public void Run() {
    String[] schoolSupplies = {
      "Backpack",
      "Pencil Case",
      "Pencil",
      "Eraser",
      "Sharpener",
      "Scissors"
    };

    for (int index = 0; index < schoolSupplies.length; index++)
      System.out.printf("schoolSupplies[%d]: %s\n", index, schoolSupplies[index]);
  }
}

// schoolSupplies[0]: Backpack
// schoolSupplies[1]: Pencil Case
// schoolSupplies[2]: Pencil
// ...

Variations of the For Loop

For-each (Enhanced For)

Java offers a variation of the for loop called for-each, which is useful for iterating over arrays or collections without the need for an index.

for (Type variable : collection) {
  // block of code
}

Using our previous example:

for (String item : schoolSupplies) {
  System.out.println(item);
}

This variation simplifies the code, making it more readable and less prone to index-related errors.

Conclusion

The for loop is an essential tool in any Java developer's toolbox. Understanding its syntax and variations can significantly simplify code, especially when dealing with repetitive operations.

Happy coding!