DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 3: `for` Loop

In Part 1, we learned about the while loop, which is ideal when the number of iterations is unknown.

In Part 2, we explored the do-while loop, which guarantees that the loop body executes at least once.

Now it's time to learn the most commonly used loop in Java—the for loop.

If you've written Java code before, chances are you've used a for loop. It's concise, flexible, and perfect when you know how many times you want to repeat an operation.

In this article, we'll cover everything from basic syntax to advanced interview questions and common compiler rules.


What Is the for Loop?

A for loop repeatedly executes a block of code until a specified condition becomes false.

It is best suited for situations where the number of iterations is known in advance.

Common examples include:

  • Printing numbers
  • Traversing arrays
  • Processing lists
  • Nested loops
  • Matrix operations
  • Algorithm implementation

Syntax

for (initialization; condition; update) {

    // loop body

}
Enter fullscreen mode Exit fullscreen mode

The for loop has three sections:

  1. Initialization – Executes once before the loop starts.
  2. Condition – Checked before every iteration.
  3. Update – Executes after each iteration.

How the for Loop Works

Execution order:

  1. Initialization
  2. Condition
  3. Loop body
  4. Update
  5. Repeat from step 2

If the condition becomes false, the loop terminates.


Your First for Loop

for (int count = 1; count <= 5; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Printing Even Numbers

for (int number = 2; number <= 10; number += 2) {

    System.out.println(number);

}
Enter fullscreen mode Exit fullscreen mode

Output

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

Understanding Each Section

1. Initialization

The initialization section executes only once.

for (int count = 1; count <= 3; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Here,

int count = 1;
Enter fullscreen mode Exit fullscreen mode

runs only once before the loop begins.


2. Condition

The condition must evaluate to a boolean.

for (int count = 1; count <= 3; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

When

count <= 3
Enter fullscreen mode Exit fullscreen mode

becomes false, the loop stops.


3. Update

The update section executes after every iteration.

count++;
Enter fullscreen mode Exit fullscreen mode

The update section can contain almost any valid Java statement.


All Three Sections Are Optional

One of the most interesting facts about the for loop is that all three sections are optional.

The following is perfectly valid:

for (;;) {

    System.out.println("Running...");

}
Enter fullscreen mode Exit fullscreen mode

This is an infinite loop.

The compiler treats the missing condition as

true
Enter fullscreen mode Exit fullscreen mode

Infinite for Loop

for (;;) {

    System.out.println("Infinite Loop");

}
Enter fullscreen mode Exit fullscreen mode

Output

Infinite Loop
Infinite Loop
Infinite Loop
...
Enter fullscreen mode Exit fullscreen mode

Multiple Variables

The initialization section can declare multiple variables.

for (int left = 1, right = 5; left <= right; left++, right--) {

    System.out.println(left + " " + right);

}
Enter fullscreen mode Exit fullscreen mode

Output

1 5
2 4
3 3
Enter fullscreen mode Exit fullscreen mode

Variables Must Be the Same Type

Correct

for (int x = 1, y = 10; x < y; x++, y--) {

}
Enter fullscreen mode Exit fullscreen mode

Incorrect

for (int x = 1, boolean finished = false; x < 5; x++) {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

Variables declared together must have the same type.


Method Calls in the Initialization Section

The initialization section isn't limited to variable declarations.

You can execute any valid Java statement.

int count = 1;

for (System.out.println("Starting Loop"); count <= 3; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Output

Starting Loop
1
2
3
Enter fullscreen mode Exit fullscreen mode

The initialization statement executes only once.


Method Calls in the Update Section

The update section can also execute method calls.

int count = 1;

for (; count <= 3; System.out.println("Next Iteration")) {

    count++;

}
Enter fullscreen mode Exit fullscreen mode

Output

Next Iteration
Next Iteration
Next Iteration
Enter fullscreen mode Exit fullscreen mode

Omitting the Initialization

Initialization is optional.

int count = 1;

for (; count <= 3; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Omitting the Update

The update can be moved into the loop body.

for (int count = 1; count <= 3;) {

    System.out.println(count);

    count++;

}
Enter fullscreen mode Exit fullscreen mode

Omitting the Condition

for (int count = 1;; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

This is another infinite loop.


Unreachable Statement Rule

Java reports an error whenever it knows that some code can never execute.


Case 1

for (int i = 0; true; i++) {

}

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

The compiler knows the loop never exits.


Case 2

for (int i = 0; false; i++) {

    System.out.println(i);

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

The loop body can never execute.


Case 3

int start = 10;
int end = 20;

for (int i = 0; start < end; i++) {

}

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

This compiles successfully.

The compiler cannot determine the values of start and end during compilation.


Effect of final

final int start = 10;
final int end = 20;

for (int i = 0; start < end; i++) {

}

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

The compiler replaces

start < end
Enter fullscreen mode Exit fullscreen mode

with

10 < 20
Enter fullscreen mode Exit fullscreen mode

which becomes

true
Enter fullscreen mode Exit fullscreen mode

The loop is now known to be infinite.


Nested for Loops

Nested loops are commonly used for matrices and patterns.

for (int row = 1; row <= 3; row++) {

    for (int column = 1; column <= 3; column++) {

        System.out.print("* ");

    }

    System.out.println();

}
Enter fullscreen mode Exit fullscreen mode

Output

* * *
* * *
* * *
Enter fullscreen mode Exit fullscreen mode

Execution Trace

for (int count = 1; count <= 3; count++) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode
Iteration count before Condition Output count after
1 1 true 1 2
2 2 true 2 3
3 3 true 3 4
4 4 false

Common Beginner Mistakes

Forgetting the Update

for (int count = 1; count <= 5;) {

    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Result

Infinite loop.


Using Assignment Instead of Comparison

boolean running = false;

for (; running = true;) {

}
Enter fullscreen mode Exit fullscreen mode

The assignment returns true, causing an infinite loop.


Using Different Variable Types

Incorrect

for (int x = 1, boolean done = false; x < 5; x++) {

}
Enter fullscreen mode Exit fullscreen mode

Variables declared together must have the same type.


Forgetting That All Sections Are Optional

Many beginners believe all three sections are mandatory.

In reality,

for (;;) {

}
Enter fullscreen mode Exit fullscreen mode

is completely valid.


Best Practices

  • Use a for loop when the number of iterations is known.
  • Keep the initialization, condition, and update simple.
  • Prefer meaningful variable names like index, row, column, or count.
  • Avoid modifying the loop variable inside the body unless necessary.
  • Use braces even for single statements.
  • Keep nested loops readable by using descriptive variable names.

Interview Questions

Which loop is most commonly used in Java?

The for loop.


Are all three sections mandatory?

No.

Initialization, condition, and update are all optional.


What happens if the condition is omitted?

The compiler treats it as

true
Enter fullscreen mode Exit fullscreen mode

creating an infinite loop.


Can method calls appear in the initialization or update section?

Yes.

Both sections can contain valid Java statements.


Why can adding final produce an unreachable statement error?

Because final variables initialized with constants become compile-time constants, allowing the compiler to determine that the loop is infinite.


while vs for

Feature while for
Best for Unknown iterations Known iterations
Initialization Outside loop Inside loop
Update Manual Built into syntax
Readability Good Excellent for counting loops

Quick Memory Trick 🧠

Remember FOR:

  • F → Fixed number of iterations
  • O → Optional sections
  • R → Repeats until the condition becomes false

Or simply remember:

"Know the count? Use for."


Key Takeaways

  • The for loop is ideal when the number of iterations is known.
  • It consists of initialization, condition, and update sections.
  • All three sections are optional.
  • Omitting the condition creates an infinite loop.
  • Multiple variables can be declared if they share the same type.
  • Method calls are allowed in the initialization and update sections.
  • final variables can affect compile-time unreachable statement analysis.
  • Nested for loops are commonly used for patterns, matrices, and algorithms.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)