for loop and nested for loop in Java

  • Last Updated: October 20, 2023
  • By: javahandson
  • Series
img

for loop and nested for loop in Java

In this article, we will learn the for loop and nested for loop in Java with simple, hands-on examples. We will start with the plain for loop, take apart its three expressions, and then put one loop inside another to draw patterns. If you want to learn about other Java topics you can click the above Java menu or you can click on this link Java topics.

1. Introduction

Computers are good at boring, repetitive work. Loops are how we hand them that work.

Say you want to print the numbers 1 to 5. You could write five print statements. Now make it 1 to 5000. Suddenly that approach looks silly.

A for loop solves this. You tell Java where to start, when to stop, and how to step forward. Java handles the rest.

1.1 What This Article Covers

  • The three expressions inside a for loop, and what each one does.
  • How to leave any of those expressions out, including the bare for(;;).
  • The enhanced for loop, which is the cleanest way to walk an array.
  • Nested loops, and the simple formula for how many times they run.
  • Star patterns, the classic beginner exercise.
  • When a while loop is the better tool.

1.2 When to Reach for a for Loop

Use a for loop when you know the number of repetitions before the loop starts. Counting to 10, walking an array of 50 items, printing 5 rows of stars — all of these have a known count.

When the count depends on something you discover as you go, a while loop fits better.

2. The for Loop Syntax

for (expression1; expression2; expression3) {
    // execute a set of statements
}

2.1 The Three Expressions

  • expression1 is the initialization. It sets up your counter and runs exactly once.
  • expression2 is the condition. Java checks it before every pass. The loop stops the moment it turns false.
  • expression3 is the update. It runs after every pass, usually to increment or decrement the counter.

All three sit on one line, which is why the for loop is easier to debug than its cousins. Everything you need to understand the loop is right there in the header.

2.2 How It Runs Step by Step

package com.java.handson.control.statements;

public class ForLoopDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}
// Output:
// 1
// 2
// 3
// 4
// 5

Follow the machine through it.

  • Java sets i = 1. This happens once and never again.
  • Java checks i <= 5. Since 1 is not more than 5, the body runs and prints 1.
  • Java runs i++, so i becomes 2. Back to the condition.
  • Steps two and three repeat until i becomes 6.
  • At i = 6 the condition is false, and control leaves the loop.

Notice the asymmetry. Initialization fires once. The condition and the update fire on every single pass.

3. The Three Expressions Are Optional

Here is something that surprises beginners. Every one of those three expressions can be left out. The semicolons must stay, but the expressions themselves are optional.

3.1 Skipping the Initialization

int i = 1;

for ( ; i <= 5; i++) {
    System.out.println(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5

We declared i above the loop instead. One real consequence follows: i now survives after the loop ends, because its scope is the whole method rather than just the loop.

3.2 Skipping the Condition and the Update

Drop all three and you get for(;;), an intentionally infinite loop. Something inside the body must now stop it, and that something is usually a break statement.

package com.java.handson.control.statements;

public class InfiniteForDemo {
    public static void main(String[] args) {
        int i = 1;

        for ( ; ; ) {
            System.out.println(i);

            if (i >= 5) {
                break;
            }
            i++;
        }
    }
}
// Output:
// 1
// 2
// 3
// 4
// 5

The condition still exists. We just moved it inside the body as an if. The update moved inside too.

One warning, because tutorials get this wrong. A loop with no exit does not throw an error. It simply runs forever and your program hangs until you kill it. Java will not rescue you from that.

4. The Enhanced for Loop

When you just want to visit every element of an array or a collection, the classic for loop is noisy. Java gives us a shorter form, often called the for-each loop.

4.1 The for-each Syntax

package com.java.handson.control.statements;

public class ForEachDemo {
    public static void main(String[] args) {
        String[] names = {"Asha", "Ravi", "Meera"};

        for (String name : names) {
            System.out.println(name);
        }
    }
}
// Output:
// Asha
// Ravi
// Meera

Read the colon as “in”. For each name in names, print it. No counter, no condition, no chance of an off-by-one mistake.

4.2 When Not to Use It

  • You need the index. The for-each loop hides it from you.
  • You want to walk backwards, or skip every second element.
  • You need to remove items while looping. Doing that here throws a ConcurrentModificationException.

In those cases, go back to the classic for loop. Otherwise prefer for-each, since less code means fewer bugs.

5. Nested for Loops

A nested for loop is simply a for loop written inside another for loop. The outer loop drives the rows. The inner loop drives the columns.

for (expression1; expression2; expression3) {
    for (expression1; expression2; expression3) {
        // execute a set of statements
    }
}

5.1 How Many Times Does It Run?

Multiply. If the outer loop runs m times and the inner loop runs n times, the inner body runs m × n times.

package com.java.handson.control.statements;

public class NestedForDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 2; j++) {
                System.out.println("i = " + i + " and j = " + j);
            }
        }
    }
}
// Output:
// i = 1 and j = 1
// i = 1 and j = 2
// i = 2 and j = 1
// i = 2 and j = 2
// i = 3 and j = 1
// i = 3 and j = 2

Three times two gives six lines, and six lines is what we got.

5.2 The Part Beginners Miss

Watch j in that output. It climbs to 2, then resets to 1 again.

The inner loop restarts completely on every pass of the outer loop. Its initialization expression runs fresh each time. The outer loop only advances once the inner loop has finished running to exhaustion.

Keep the cost in mind too. Two nested loops over 1,000 items each means a million passes. Nesting multiplies work fast.

6. Drawing Patterns

Star patterns are the classic exercise here, and they are a genuinely good one. The trick is to make the inner loop depend on the outer counter.

6.1 A Growing Triangle

package com.java.handson.control.statements;

public class PatternDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
// Output:
// *
// **
// ***
// ****
// *****

Look at the inner condition: j <= i, not j <= 5. Row 1 prints one star, row 2 prints two, and the triangle grows. That single character is the whole idea.

The bare System.out.println() after the inner loop just ends the line. Without it, every star would land on one long row.

6.2 A Shrinking Triangle

package com.java.handson.control.statements;

public class ReversePatternDemo {
    public static void main(String[] args) {
        for (int i = 5; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
// Output:
// *****
// ****
// ***
// **
// *

Flip the outer loop to count down and the triangle flips with it.

Be careful with the stopping point. Write i >= 0 instead of i >= 1 and you get one extra pass where i is zero. The inner loop prints nothing, but the println still fires, so you are left with a stray blank line.

7. for vs while vs do-while

Point for while do-while
Best when You know the count upfront The count depends on a condition The body must run at least once
Condition checked Before each pass Before each pass After each pass
Minimum runs Zero Zero One
Counter lives In the loop header Outside the loop Outside the loop
Typical use Walking an array of 50 items Reading until the user types “quit” Showing a menu, then asking again

The practical difference is bookkeeping. A for loop keeps the counter, the condition and the update together. A while loop scatters them, which is exactly how people forget the increment and hang the program.

8. Common Mistakes and Pitfalls

  • The off-by-one error. Writing i <= array.length reads past the end and throws ArrayIndexOutOfBoundsException. Valid indexes run from 0 to length - 1, so the condition you want is i < array.length.
  • A stray semicolon. Type for (int i = 0; i < 5; i++); and that semicolon becomes the entire body. The loop spins five times doing nothing, and the block below it runs once.
  • Forgetting the update. No increment means the condition never turns false. Your program hangs. It does not crash, and it does not warn you.
  • Changing the counter inside the body. Editing i in two places makes a loop very hard to follow. Let the header own the counter.
  • Reusing the same variable in both loops. A nested loop needs its own counter. Use i and j, never i twice.
  • Nesting too deep. Three levels is already hard to read, and the cost multiplies at every level. Pull the inner loop into its own method instead.

9. A Practical Walkthrough

Let us build something real: a multiplication table. Rows and columns map perfectly onto an outer and an inner loop.

package com.java.handson.control.statements;

public class MultiplicationTable {
    public static void main(String[] args) {
        int size = 5;

        for (int row = 1; row <= size; row++) {
            for (int col = 1; col <= size; col++) {
                System.out.print(row * col + "\t");
            }
            System.out.println();
        }
    }
}
// Output:
// 1    2    3    4    5
// 2    4    6    8    10
// 3    6    9    12   15
// 4    8    12   16   20
// 5    10   15   20   25

Three things are worth pulling out of this.

  • The counters are named row and col, not i and j. Good names turn a nested loop from a puzzle into a sentence.
  • The value printed is row * col, so the body uses both counters. That is what makes it a table rather than five identical lines.
  • The println() sits in the outer loop, not the inner one. It fires once per row, exactly where a line should end.

Change size to 10 and you get a ten-by-ten table without touching anything else. That is the payoff for putting the logic in the loop instead of in your typing.

10. Interview Questions

Q: What is a nested for loop in Java?

A: A nested for loop is a for loop placed inside another for loop. The inner loop completes all of its iterations for every single iteration of the outer loop. Programmers use this shape for grids, tables and star patterns.

Q: How many times does a nested for loop run?

A: Multiply the two counts. If the outer loop runs m times and the inner loop runs n times, the inner body executes m × n times. An outer loop of 5 and an inner loop of 4 gives 20 passes.

Q: Can we write a for loop without initialization, condition and update?

A: Yes. Writing for(;;) is legal and creates an infinite loop. You must keep the two semicolons, and you must put a break statement inside the body, otherwise the program runs forever.

Q: What is the difference between a for loop and an enhanced for loop?

A: A classic for loop gives you an index, so you can walk backwards, skip elements or use the position. An enhanced for loop hides the index and simply hands you each element in turn. Prefer for-each when you only need the values.

Q: When should I use a for loop instead of a while loop?

A: Use a for loop when you know the number of repetitions before the loop starts, such as walking an array. Use a while loop when the number of repetitions depends on a condition you discover as you go.

Q: How many nested for loops can we write in Java?

A: The language sets no practical limit on nesting depth. Readability sets the real one. Most production code stops at two levels, and three is already a sign that the inner loop belongs in its own method.

11. Conclusion

Let us wrap up what we covered.

A for loop packs three things into one line: where to start, when to stop, and how to step. Initialization runs once. The condition and the update run on every pass. Any of the three can be dropped, and dropping all of them gives you for(;;), which needs a break to ever finish.

Nesting one loop inside another gives you grids. The inner loop restarts on every outer pass, and the body runs m × n times. Make the inner condition depend on the outer counter and you can draw patterns.

Reach for the enhanced for loop whenever you only need the elements. Reach for a while loop when you cannot count the passes in advance.

Now go type the star patterns yourself. Change a <= to a <, flip a counter, and watch what breaks. That is how loops stop being scary.

12. Further Reading

Leave a Comment