Java For Loop
When you know how many times something should repeat, the for loop is the clearest choice. It puts the three parts of a counting loop on one line: where the counter starts, how long the loop runs, and how the counter changes. You already know these parts from the While Loop topic; for just keeps them together.
The parts of a for loop
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Line " + i);
}
}
}Line 1 Line 2 Line 3 Line 4 Line 5
int i = 1runs once, before the loop starts.i <= 5is checked before every round; when it is false, the loop ends.i++runs after every round.
The variable i exists only inside the loop. After the closing bracket it is gone; this is explained further in the Scope topic.
Other steps
The step can be anything: count by twos, count down, or multiply:
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
for (int p = 1; p <= 1000; p *= 10) {
System.out.print(p + " ");
}
System.out.println();
}
}0 2 4 6 8 10 5 4 3 2 1 1 10 100 1000
A multiplication table
Loops and printf from String Formatting work well together:
public class Main {
public static void main(String[] args) {
int n = 7;
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %3d%n", n, i, n * i);
}
}
}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 loops
A loop inside another loop runs completely for every round of the outer loop. Nested loops are used for tables, grids and patterns:
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
}
}* ** *** ****
The outer loop counts the rows. The inner loop prints as many stars as the row number, then println() ends the line. With 4 rows the inner loop runs 1 + 2 + 3 + 4 = 10 times in total.
Choosing a loop
Use for when you count (from 1 to 10, over the positions of a string or an array). Use while when you repeat until something happens. Both can do the same job; pick the one that reads more clearly. To walk through all the items of an array or a list there is an even simpler form, the for-each loop, which you will meet in the Arrays topic.
Practice exercises
- Print the squares of the numbers from 1 to 10.
- Print every character of the word "Programming" on its own line, using
charAtandlength(). - Print a 5 by 5 square of
#characters with nested loops.