HOME HTML EDITOR C JAVA PHP

Java For Loop: Precise Iteration

When you know exactly how many times you want to loop through a block of code, the for loop is your best tool. It is more concise than a while loop because it manages initialization, condition, and increment in a single line.

Efficiency Tip: The for loop is the industry standard for iterating over arrays and collections where the size is known beforehand.

1. The For Loop Syntax

A for loop consists of three main parts separated by semicolons:

2. Logical Flow

The flow starts with initialization, then checks the condition. If true, it runs the code, updates the variable, and checks the condition again.

3. Difference: For Loop vs For-Each Loop

Java also offers an enhanced version of the for loop specifically for collections and arrays:

Standard For Loop

Gives you full control over the index. Best when you need to skip elements or change values at specific positions.

For-Each Loop

Used exclusively to loop through elements in an array. It is more readable and reduces the chance of "Off-by-one" errors.

Nested For Loop

A loop inside another loop. Commonly used for processing 2D arrays or matrices.

4. Key Variations

You can customize how the loop progresses by changing the third statement:

  1. Incrementing: i++ or i += 2 to move forward.
  2. Decrementing: i-- to loop backwards (useful for reverse sorting).
  3. Infinite: for(;;) creates a loop that never stops unless a break is called.

5. Comparison Table

Feature For Loop For-Each Loop
Index Access Available (via i) Not available
Syntax Complexity Higher (3 parts) Lower (Simplified)
Primary Use General purpose logic Arrays and Collections only

6. Code Example

// Standard For Loop
for (int i = 0; i < 5; i++) {
  System.out.println("Iteration: " + i);
}

// For-Each Loop Example
String[] cars = {"Volvo", "BMW", "Ford"};
for (String c : cars) {
  System.out.println(c);
}

Final Verdict

The for loop is the workhorse of Java programming. Whether you are iterating over simple lists or complex data structures, mastering this loop is essential for writing clean, performant code.

Next: Learn Java Arrays →