for Loop in Java: Its Types and Examples
The for loop in Java is used to repeat a block of code a specific number of times. It's one of the most commonly used loops because it combines initialization, condition checking, and updating in a single, compact line.
Standard for Loop Syntax
for (initialization; condition; update) {
// code to repeat
}
Basic Example
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// prints 1 2 3 4 5
How the for Loop Works
- Initialization runs once, before the loop starts
- The condition is checked before every iteration — the loop runs only while it's
true - The update statement runs after each iteration, typically incrementing or decrementing a counter
Enhanced for-each Loop
Introduced to simplify iterating over arrays and collections, the for-each loop removes the need for an index variable entirely.
int[] numbers = {10, 20, 30};
for (int num : numbers) {
System.out.println(num);
}
Nested for Loop
A for loop placed inside another for loop, commonly used for working with grids, matrices, or patterns.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(i + "-" + j);
}
}
Infinite for Loop
Leaving all three parts of the for loop empty creates an infinite loop, which must be stopped manually with a break statement.
for (;;) {
// runs forever unless broken out of
}
for loop when you know exactly how many times to repeat something, and switch to the for-each version whenever you're simply iterating over every element of a collection.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.
Practical Examples Worth Practising
These short programs use the loop in ways you will meet in interviews and real code.
Sum of even numbers up to 20
int sum = 0;
for (int i = 2; i <= 20; i += 2) {
sum += i;
}
System.out.println(sum); // 110
Stepping by 2 skips the odd numbers completely, so no if check is needed inside the loop.
Two variables moving towards each other
int[] arr = {1, 2, 3, 4, 5};
for (int left = 0, right = arr.length - 1; left < right; left++, right--) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
// arr is now {5, 4, 3, 2, 1}
The initialization and update parts can each hold several comma-separated statements, which is handy for reversing arrays and checking palindromes.
A star triangle with nested loops
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("* ");
}
System.out.println();
}
The outer loop controls the rows, and the inner loop prints as many stars as the current row number.
Controlling the Flow with break, continue and Labels
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue; // skip multiples of 3
if (i > 8) break; // stop the loop entirely
System.out.print(i + " "); // 1 2 4 5 7 8
}
outer:
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 5; c++) {
if (r * c == 6) {
System.out.println("Found at " + r + "," + c);
break outer; // leaves both loops at once
}
}
}
A plain break inside a nested loop exits only the inner loop. A label lets you jump out of the outer loop directly, which avoids extra flag variables.
Choosing Between for, for-each and Other Loops
When you are unsure, ask two questions: do I need the index, and do I know how many times to repeat? If you need neither, the for-each loop is the cleanest. If you need the index, or want to step backwards or skip elements, the standard form gives full control.
| Need | Best choice |
|---|---|
| Known number of repetitions or need the index | Standard for loop |
| Read every element of an array or collection | Enhanced for-each |
| Repeat until a condition changes, count unknown | while loop |
| Run the body at least once | do-while loop |
| Remove items from a list while looping | Iterator with remove(), or removeIf() |
Bugs That Hide in for Loops
- Off-by-one errors:
i <= arr.lengthreads one element past the end and throwsArrayIndexOutOfBoundsException. Usei < arr.length. - Stray semicolon:
for (int i = 0; i < 5; i++);runs an empty body five times, and the block below runs once. - Using the variable after the loop: a variable declared in the header exists only inside the loop.
- Changing a list inside for-each: calling
list.remove()usually throwsConcurrentModificationException. - Assigning to the for-each variable:
num = 0changes only the local copy, not the array element. - Double counters:
for (double d = 0; d != 1.0; d += 0.1)may never stop because of rounding. Use integer counters instead.