Loops
Prerequisites: Switch statements & expressions
Java has three main loop forms: the counting for, the condition
while, and the collection-walking enhanced for (for-each).
Syntax
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}
Example
for (int i = 1; i <= 3; i++) {
System.out.println("Count: " + i);
}
Expected output
Count: 1
Count: 2
Count: 3
Common mistakes
- Writing
i <= nums.lengthinstead ofi < nums.lengthwhen indexing an array by hand — this reads one past the end and throwsArrayIndexOutOfBoundsException. - An infinite loop from forgetting to update the loop variable inside
a
whilebody.
Practice
Print the numbers 1 through 5 using a for loop.
Show solution
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}