Syntax
for (initialization; condition; update) {\n // code\n}Examples
Basic for Loop
The classic counting loop with initialization, condition, and update.
for (int i = 0; i < 5; i++) {
System.out.println(i); // 0, 1, 2, 3, 4
}Enhanced for-each Loop
A simpler syntax for iterating over every element of an array or collection.
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
String[] names = {"John", "Zain", "Jamal"};
for (String name : names) {
System.out.println("Hello, " + name);
}Nested for Loops
A loop inside another loop, commonly used for working with grids or generating combinations.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print(row * col + " ");
}
System.out.println();
}for Loop with Multiple Variables
Java's for loop can initialize and update more than one variable at once.
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}Best practices
- Use the enhanced for-each loop whenever you only need each element, not its index - it is safer and more readable
- Use a traditional for loop when you need the index, need to iterate backward, or need to skip elements with a custom step
- Avoid modifying the loop counter variable inside the loop body - it can create subtle, hard-to-follow bugs
- Prefer for over while when the number of iterations is known in advance, since it groups all loop control in one place
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification