for loop and nested for loop in Java
-
Last Updated: October 20, 2023
-
By: javahandson
-
Series
Learn Java in a easy way
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.
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.
for loop, and what each one does.for(;;).for loop, which is the cleanest way to walk an array.while loop is the better tool.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.
for (expression1; expression2; expression3) {
// execute a set of statements
}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.
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
// 5Follow the machine through it.
i = 1. This happens once and never again.i <= 5. Since 1 is not more than 5, the body runs and prints 1.i++, so i becomes 2. Back to the condition.i becomes 6.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.
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.
int i = 1;
for ( ; i <= 5; i++) {
System.out.println(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5We 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.
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
// 5The 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.
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.
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
// MeeraRead the colon as “in”. For each name in names, print it. No counter, no condition, no chance of an off-by-one mistake.
ConcurrentModificationException.In those cases, go back to the classic for loop. Otherwise prefer for-each, since less code means fewer bugs.
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
}
}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 = 2Three times two gives six lines, and six lines is what we got.
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.
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.
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.
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.
| 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.
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.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.i in two places makes a loop very hard to follow. Let the header own the counter.i and j, never i twice.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 25Three things are worth pulling out of this.
row and col, not i and j. Good names turn a nested loop from a puzzle into a sentence.row * col, so the body uses both counters. That is what makes it a table rather than five identical lines.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.
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.
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.
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.
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.
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.
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.
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.