for Loops
When you know how many times to repeat — or you're walking through a range of numbers or the items of a collection — the for loop is the natural choice. It keeps the counter's start, condition and update together in one line, and the enhanced for-each loop makes iterating over arrays and lists effortless.
The counting for loop
void main() { for (int i = 1; i <= 5; i++) { System.out.println("Step " + i); } }
Step 1 Step 2 Step 3 Step 4 Step 5
The header has three parts separated by semicolons:
- Initialisation —
int i = 1, runs once before the loop. - Condition —
i <= 5, checked before each repetition. - Update —
i++, runs after each repetition.
The variable i exists only inside the loop.
Other step sizes
void main() { for (int i = 10; i > 0; i -= 3) { System.out.print(i + " "); } System.out.println(); for (int i = 0; i <= 100; i += 25) { System.out.print(i + " "); } System.out.println(); }
10 7 4 1 0 25 50 75 100
Accumulating a result
void main() { int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } System.out.println("1 + 2 + … + 100 = " + sum); long factorial = 1; for (int i = 2; i <= 15; i++) { factorial *= i; } System.out.println("15! = " + factorial); }
1 + 2 + … + 100 = 5050 15! = 1307674368000
The for-each loop
void main() { String[] colours = {"red", "green", "blue"}; for (String colour : colours) { System.out.println(colour.toUpperCase()); } int total = 0; for (int n : new int[]{4, 8, 15, 16, 23, 42}) { total += n; } System.out.println(total); }
RED GREEN BLUE 108
Read for (String colour : colours) as "for each colour in colours". It works with arrays and every collection (lists, sets…), and avoids index mistakes. Use the counting loop when you need the index or want to skip or modify elements by position.
Off-by-one errors
void main() { int[] numbers = {5, 6, 7}; for (int i = 0; i <= numbers.length; i++) { System.out.println(numbers[i]); } }
5
6
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main.java:4)Indexes run from 0 to length - 1, so the condition must be i < numbers.length. Using <= is the classic off-by-one mistake.
Multiple variables
void main() { String word = "level"; boolean palindrome = true; for (int i = 0, j = word.length() - 1; i < j; i++, j--) { if (word.charAt(i) != word.charAt(j)) { palindrome = false; } } System.out.println(word + " is a palindrome: " + palindrome); }
level is a palindrome: true
A for header can declare and update several variables, separated by commas — here two indexes walking towards each other.
Try it yourself
Print a multiplication table for 7 with aligned columns.
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49 8 x 7 = 56 9 x 7 = 63 10 x 7 = 70