Java for Loop
What is a for Loop?
A for loop repeats a block of code a known number of times. It packs the three things every counting loop needs — where to start, when to stop, and how to move forward — into a single, tidy header line.
Basic Syntax
for (initialization; condition; update) {
// code to repeat
}initialization runs once, before the loop starts (usually declares a counter).
condition is checked before every iteration — the loop keeps running while it's true.
update runs after every iteration (usually increments or decrements the counter).
A Simple Example
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Counting Down
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Liftoff!");5 4 3 2 1 Liftoff!
Multiple Init and Update Expressions
The header isn't limited to a single variable. You can initialize and update more than one variable at once by separating them with commas — handy when two counters need to move together.
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i + ", j = " + j);
}i = 0, j = 10 i = 1, j = 9 i = 2, j = 8 i = 3, j = 7 i = 4, j = 6
Nested for Loops
A for loop can contain another for loop. This is the standard tool for working with grids, tables, and anything two-dimensional — the outer loop picks a row, the inner loop walks across the columns of that row.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print(row + "," + col + " ");
}
System.out.println();
}1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3
Classic for vs Enhanced for
Java also has an enhanced for loop (the "for-each" loop) that reads more naturally when you just want to visit every element of an array or collection without caring about the index. It's covered in detail on the next page — but as a quick preview:
Situation | Better Choice |
You need the index (e.g., i, or comparing i to another counter) | Classic for |
You're counting up/down, skipping values, or using multiple counters | Classic for |
You just want every element of an array/collection, in order | Enhanced for |
You want to modify elements by index (arr[i] = ...) | Classic for |
Practice Exercises
Print all even numbers between 1 and 20 using a for loop.
Print a multiplication table for a given number using a for loop.
Use a nested for loop to print a triangle pattern of asterisks.
Use two counters in one for loop header to print pairs that add up to 10.