When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
for LoopThe example below will print the numbers 0 to 4.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
i to 0 before the loop starts.i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.i by 1 (i++) each time the code block in the loop has been executed.There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other collections).
Syntax:
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in the cars array, using a "for-each" loop.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
System.out.println(car);
}
}
}
The for-each loop is generally more readable and less error-prone than a standard for loop when you just need to iterate over all elements of a collection.