AI Hints
Home›Java Tutorial›while Loops, do while and for Loops
Java · Lesson 39 of 120

for Loops

Counting loops.

⏱ 2 min read▶ Video at 49:53🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When you know how many times to repeat, a for loop is the neatest choice. It keeps the start, the condition, and the step, all in one line.

  • A known number of times
  • Start, condition, step
  • All in one line

The three parts

A for loop has three parts, separated by semicolons. The start runs once, before the loop. The condition is checked before every lap. And the step runs after every lap.

keyvalue
int i = 1start: runs once
i <= 5condition: before each lap
i++step: after each lap
ithe loop counter

Five laps

I starts at one. While I is five or less, the body runs. After each lap, I goes up by one. Run it. Five laps, then the race is over.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Lap " + i);
        }
        System.out.println("Race over");
    }
}
Output
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Race over

Other steps

The step can be anything. Plus equals five counts in fives. Minus minus counts down. Run it. Zero to twenty in fives, and a countdown, from ten to one.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i <= 20; i += 5) {
            System.out.print(i + " ");
        }
        System.out.println();
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println("Lift off!");
    }
}
Output
0 5 10 15 20
10 9 8 7 6 5 4 3 2 1 Lift off!

Summary

A for loop has a start, a condition, and a step. It's the best choice when you know how many times to repeat. Next, break and continue.

Key takeaways
  • for (start; cond; step)
  • Count up or down
  • Any step size
Next up: break and continue — leave or skip