Java for Loop

In the last lesson you learned about the Java switch statement. Now meet one of the biggest ideas in programming: repeating work without copying code.

Want to print 1 to 100? You write a loop, not 100 print lines. The for loop is perfect when you know how many times to repeat.

๐Ÿค” Why do we need loops?

Say you want to print โ€œHelloโ€ five times. The clumsy way is to copy the line.

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

A loop is the โ€œrepeatโ€ button for code: write the action once, tell Java how many times to run it.

  • Copying a line a thousand times is not realistic.
  • Change the text tomorrow? With copies you fix every one by hand, and one miss breaks the output.
  • The repeated lines inside the curly braces are the body of the loop.
  • Result: less code, fewer mistakes, easier to change.

๐Ÿงฉ The for loop syntax

A for loop packs three parts into one line, separated by exactly two semicolons.

for (initialization; condition; update) {
// the code to repeat
}

Each part has one job.

  • Initialization runs once at the start. It usually creates a counter, like int i = 0.
  • Condition is a yes-or-no question checked before every run. true keeps the loop going, false stops it.
  • Update runs after each repeat. It usually steps the counter forward, like i++.

Here is a real one that prints the numbers 1 to 5.

for (int i = 1; i <= 5; i++) {
System.out.println(i);
}

Read it as a sentence: start i at 1, keep going while i is 5 or less, add 1 after each run. So it prints 1 to 5, then stops when i becomes 6.

Output

1
2
3
4
5

The starting value, the stopping question, and the step all sit on one line. That is what makes a for loop easy to read.

๐Ÿ” The exact order each run happens

The three parts do not run top to bottom. They run in a fixed order, and knowing it removes the confusion.

  • Init runs once. int i = 1 happens a single time, at the start, and never again.
  • Check the condition. Is i <= 5 true? Yes, go on. No, the loop ends now.
  • Run the body. The code inside the braces prints the current i.
  • Run the update. i++ changes i, then jump back to the condition check.

So the cycle is check, body, update, repeat.

  • The update runs after the body, every pass.
  • The condition is checked before the body, every pass.
  • If the condition is false on the first check, the body never runs at all.

Here is the full trace of the 1-to-5 loop.

Step Value of i Is i <= 5? What happens
init 1 โ€” i is set to 1
pass 1 1 true print 1, then i becomes 2
pass 2 2 true print 2, then i becomes 3
pass 3 3 true print 3, then i becomes 4
pass 4 4 true print 4, then i becomes 5
pass 5 5 true print 5, then i becomes 6
final check 6 false loop stops, nothing prints

In the last row i becomes 6, so 6 <= 5 is false, the body skips, and 6 never prints. The loop ran exactly five times.

Any time a loop confuses you, write a table like this and walk it row by row.

Why is it called i?

The counter is traditionally called i, short for โ€œindexโ€, which means a position number. For nested loops you will also see j and k. It is just a habit, but it is so common that other developers expect it. You can use a clearer name when it helps, like row or count.

๐Ÿงฎ A practical example

Loops do real work, not just printing numbers. This one adds up 1 to 10 to find the total.

int total = 0;
for (int i = 1; i <= 10; i++) {
total = total + i;
}
System.out.println("The total is " + total);
  • int total = 0 sits outside the loop as the running sum, starting at zero.
  • Each pass adds the current i into total, so it grows by 1, then 2, all the way to 10.
  • The println is also outside, so it runs once at the end after all the adding.

total is an accumulator: a variable that collects a result across passes. Declare it before the loop, change it inside, read it after. The same pattern handles summing, counting, building text, and finding the biggest value.

Output

The total is 55

๐Ÿ”ข Counting down and custom steps

Change the update part and you can count down or jump by bigger amounts. First, counting down from 5 to 1.

for (int i = 5; i >= 1; i--) {
System.out.println(i);
}

All three parts flip to count the other way.

  • The start is now 5, the high number.
  • The condition i >= 1 keeps going while i is 1 or more.
  • The update i-- subtracts 1 each pass.

Output

5
4
3
2
1

Now a custom step: move by any amount, not just 1. This prints the even numbers from 0 to 10 with i += 2.

for (int i = 0; i <= 10; i += 2) {
System.out.println(i);
}
  • i += 2 means โ€œadd 2 to iโ€, so i goes 0, 2, 4, 6, 8, 10.
  • At 12 the check fails and the loop stops.
  • The update controls the jump size: i -= 2 steps down, any number works.

Output

0
2
4
6
8
10

๐Ÿ“‹ Looping over a range of values

The for loop is built for walking a range, like days 1 to 31 or hours 0 to 23. Set the start and end, then use i inside the body. Here is a times-table for 7.

int number = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
  • The range is 1 to 10, and i is the next value on each pass.
  • We use i to build one line of the table.
  • So i is not only the loop counter, it is also a value for real calculations.

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

๐Ÿ”ฒ Nested for loops

Put a for loop inside another for loop and you get a nested loop, the tool for grids, tables, and rows-and-columns work. The outer loop picks the row, the inner loop walks across it.

Letโ€™s print a 3 by 3 grid of stars.

for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("* ");
}
System.out.println(); // โœ… move to the next line after each row
}
  • The outer loop starts at row = 1.
  • The inner loop runs fully, all 3 columns, printing three stars on that row.
  • The outer loop then updates to row = 2 and the inner loop runs fully again.
  • Key rule: the inner loop runs all the way through for every single step of the outer loop.
  • So 3 rows times 3 columns means the inner body runs 9 times, and the empty println() ends each rowโ€™s line.

Output

* * *
* * *
* * *

A real use is a multiplication table, where the inner loop multiplies the row by each column.

for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print((row * col) + "\t"); // \t adds a tab gap
}
System.out.println();
}

Output

1 2 3
2 4 6
3 6 9

Notice row stays fixed while col runs across. That is the heart of every grid: the outer value holds steady while the inner value sweeps its whole range.

Use different counter names

Always give the inner loop a different counter name than the outer one, like row and col, or i and j. If both loops use i, they fight over the same variable and the logic breaks.

๐ŸŽฏ Off-by-one errors and the boundary

The most common loop bug is the off-by-one error: the loop runs one time too many or too few. It almost always comes down to < versus <=.

// Runs for i = 1, 2, 3, 4 (stops before 5)
for (int i = 1; i < 5; i++) {
System.out.println(i);
}
// Runs for i = 1, 2, 3, 4, 5 (includes 5)
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
  • < stops before 5, so the first loop runs 4 times.
  • <= includes 5, so the second runs 5 times.
  • Boundary trick: start at 1 with i <= N, or start at 0 with i < N. Both give N passes.
  • Start at 0 with < is the common Java style, especially with arrays.

Before writing a loop, ask: should the last value be included? Then pick < or <= to match.

โš ๏ธ Common Mistakes

A few slip-ups, including ones that freeze your program.

Forgetting the update, which creates an infinite loop. If the counter never changes, the condition never becomes false and the loop runs forever.

// โŒ Wrong: i never changes, so i <= 5 is always true. This never stops.
// for (int i = 1; i <= 5; ) {
// System.out.println(i);
// }
// โœ… Right: i++ moves i toward the stopping point, so the loop ends
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}

An update that moves the wrong way. An update that pushes away from the condition also runs forever. Counting up while the condition wants you to come down never stops.

// โŒ Wrong: i starts at 1 and keeps growing, but the condition wants i >= 1
// for (int i = 1; i >= 1; i++) { // i is always >= 1, runs forever
// System.out.println(i);
// }
// โœ… Right: count down so i actually reaches the stopping point
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}

A semicolon right after the for line. A stray semicolon ends the loop early, so it repeats nothing and the block below runs only once.

// โŒ Wrong: the ; makes the loop body empty. The block below runs just once.
// for (int i = 1; i <= 5; i++);
// {
// System.out.println(i); // prints only 6, one time
// }
// โœ… Right: no semicolon, so the block is the loop body
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}

Using the counter after the loop ends. A counter declared with int i inside the for only exists inside the loop. That is the next section.

๐Ÿ”’ Loop variable scope

When you write for (int i = 1; ...), i belongs to the loop and nowhere else. That region where a variable is allowed to exist is its scope. Once the loop ends, i is gone, and using it afterward will not compile.

for (int i = 1; i <= 5; i++) {
System.out.println(i); // โœ… i works fine here, inside the loop
}
// System.out.println(i); // โŒ Error: i does not exist out here

This is a good thing: counters cannot leak into the rest of your code. But when you do want the final value, declare the variable before the loop.

int i; // declared outside, so it stays after the loop
for (i = 1; i <= 5; i++) {
System.out.println(i);
}
System.out.println("Loop ended with i = " + i); // โœ… now this works, prints 6
  • Declare i inside the for when you only need it during the loop (most of the time).
  • Declare it outside when you need its value after the loop finishes.

โœ… Best Practices

Habits for clean, correct for loops.

  • Use for when you know the count. If you do not know the count, a while loop fits better.
  • Always change the counter. Move the update toward the stopping condition, never away, or you get an infinite loop.
  • Mind the boundary. Choose < or <= by asking whether the last value should be included.
  • Declare the counter inside the for. Keep i scoped to the loop unless you need its value afterward.
  • Give nested loops different names. Use row and col, or i and j, so they never clash.
  • Keep the body focused. Do one clear job inside the loop, and move big work into a method later.

๐Ÿงฉ What Youโ€™ve Learned

You can now repeat work without copying a single line. Quick recap.

  • โœ… A for loop repeats code a set number of times without copying lines.
  • โœ… It has three parts: initialization (runs once), condition (checked before each run), and update (after each run).
  • โœ… The exact order is: init once, then check condition, run body, update, then check again.
  • โœ… You can count up, count down, or step by any amount like i += 2 by changing the parts.
  • โœ… Nested loops handle grids and tables, with the inner loop running fully for each step of the outer loop.
  • โœ… < vs <= controls the count, a wrong update causes an infinite loop, and a stray semicolon empties the body.
  • โœ… A counter declared inside the for has loop scope, so it disappears once the loop ends.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Which part of a for loop runs only once?

    Why: The initialization (like int i = 1) runs once at the very start. The condition and update repeat every pass.

  2. 2

    In a for loop, when does the update (like i++) run?

    Why: The order is init once, then check condition, run body, update, then check again. The update runs after the body on each pass.

  3. 3

    How many times does for (int i = 0; i < 5; i++) run?

    Why: It runs for i = 0, 1, 2, 3, 4, which is 5 times, then stops when i becomes 5 because i < 5 is false.

  4. 4

    In a nested for loop, how often does the inner loop run?

    Why: The inner loop runs all the way through for each step of the outer loop. A 3 by 3 grid runs the inner body 9 times.

๐Ÿš€ Whatโ€™s Next?

The for loop is perfect when you know the count. But what if you do not? Like โ€œkeep asking until the user types quitโ€. For that, you use a while loop. Letโ€™s learn it next.

Java while Loop

Share & Connect