for Loop in Java – Syntax and Examples
A loop repeats a block of code. The for loop is Java's go-to loop when you know how many times to repeat, or when you count through a range such as the indexes of an array. It keeps the three parts of counting, start, stop and step, together in one line.
This tutorial explains the syntax and flow of the for loop, shows how to loop over arrays and strings, covers nested loops and variations, and lists the mistakes to avoid.
1. Syntax of the for Loop
for (initialization; condition; update) {
// loop body
}
| Part | Runs | Typical example |
|---|---|---|
| Initialization | Once, before the loop starts | int i = 0 |
| Condition | Before every iteration; the loop stops when it is false | i < 10 |
| Body | Each time the condition is true | The statements in { } |
| Update | After every iteration | i++ |
2. How the Loop Runs
- Run the initialization.
- Check the condition. If it is
false, leave the loop. - Run the body.
- Run the update, then go back to step 2.
If the condition is false at the very start, the body never runs.
3. Basic Examples
public class ForBasics {
public static void main(String[] args) {
// init; condition; update
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
for (int n = 1; n <= 100; n++) {
sum += n;
}
System.out.println("Sum of 1..100 = " + sum);
System.out.print("Even numbers counting down: ");
for (int i = 10; i >= 0; i -= 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
1 2 3 4 5 Sum of 1..100 = 5050 Even numbers counting down: 10 8 6 4 2 0
The update can be anything: i++, i--, i += 2 or even i *= 2.
4. Looping Over Arrays and Strings
Arrays and strings are indexed from 0 to length - 1, which matches the classic loop for (int i = 0; i < arr.length; i++). A for loop with an index is the right choice when you need the position, want to go backwards, or skip elements.
public class ForWithArrays {
public static void main(String[] args) {
int[] temps = {31, 35, 29, 38, 33};
int max = temps[0];
for (int i = 1; i < temps.length; i++) { // valid indexes: 0 .. length - 1
if (temps[i] > max) max = temps[i];
}
System.out.println("Highest temperature: " + max);
System.out.print("Reversed: ");
for (int i = temps.length - 1; i >= 0; i--) {
System.out.print(temps[i] + " ");
}
System.out.println();
String word = "loop";
for (int i = 0; i < word.length(); i++) {
System.out.println("char " + i + " = " + word.charAt(i));
}
}
}
Highest temperature: 38 Reversed: 33 38 29 35 31 char 0 = l char 1 = o char 2 = o char 3 = p
Note that arrays use the field length, while strings use the method length(). When you only need each element in order, the for-each loop is simpler.
5. Nested for Loops
A loop inside another loop is a nested loop. The inner loop completes all of its iterations for each iteration of the outer loop, which makes nested loops ideal for tables, grids, matrices and patterns.
public class NestedFor {
public static void main(String[] args) {
// Multiplication table: the inner loop runs fully for every outer iteration
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 5; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
// A simple triangle pattern
for (int line = 1; line <= 4; line++) {
System.out.println("*".repeat(line));
}
}
}
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 * ** *** ****
With n outer and m inner iterations, the body runs n × m times, so nested loops over large data can be slow. For more patterns, see Java Pattern Programs.
6. Variations of the for Loop
public class ForVariations {
public static void main(String[] args) {
// Two variables in one loop
for (int left = 0, right = 6; left < right; left++, right--) {
System.out.print("(" + left + "," + right + ") ");
}
System.out.println();
// All three parts are optional: this is an infinite loop ended by break
int attempts = 0;
for (;;) {
attempts++;
if (attempts == 3) break;
}
System.out.println("Stopped after " + attempts + " attempts");
// The loop variable is not visible after the loop
int i;
for (i = 0; i < 4; i++) { }
System.out.println("i declared outside the loop ends at " + i);
// Counting with doubles accumulates rounding errors: loop on integers instead
for (int step = 0; step <= 3; step++) {
double value = step / 10.0;
System.out.print(value + " ");
}
System.out.println();
}
}
(0,6) (1,5) (2,4) Stopped after 3 attempts i declared outside the loop ends at 4 0.0 0.1 0.2 0.3
- Separate several variables with commas in the initialization and update parts (they must share one type).
- All three parts are optional;
for (;;)is an infinite loop that needsbreakorreturnto end. - A variable declared in the initialization exists only inside the loop. Declare it before the loop if you need its final value.
- Count with integers and compute decimals from them (
step / 10.0); adding0.1repeatedly to adoubleaccumulates rounding errors.
7. Controlling the Loop: break and continue
breakexits the loop immediately. See break statement.continueskips the rest of the current iteration and moves to the update. See continue statement.- Labeled
breakandcontinuecan exit or continue an outer loop from inside a nested loop.
8. for vs while vs do-while vs for-each
| Loop | Best for | Checks condition |
|---|---|---|
for | Counting, index-based loops, known number of iterations | Before each iteration |
| while | Unknown number of iterations, waiting for a condition | Before each iteration |
| do-while | Bodies that must run at least once, such as menus | After each iteration |
| for-each | Reading every element of an array or collection | Automatically |
9. Common Mistakes
- Off-by-one errors:
i <= arr.lengthreads one element too many and throwsArrayIndexOutOfBoundsException; usei < arr.length. - A semicolon after the header:
for (int i = 0; i < 5; i++);has an empty body, so the block below runs only once. - Infinite loops from a condition that never becomes false, for example
i--instead ofi++. - Changing the loop variable inside the body, which makes the loop hard to follow.
- Modifying a collection while looping over it with an index, which shifts elements and skips some.
10. Summary
- A
forloop has initialization, condition and update parts, and runs its body while the condition is true. - It is ideal for counting and index-based work on arrays and strings.
- Nested loops handle tables and grids; their cost multiplies.
- All header parts are optional;
for (;;)is an infinite loop. - Watch out for off-by-one errors and stray semicolons.
Related Tutorials
Reference: Oracle Java Tutorials: The for Statement
Frequently Asked Questions (FAQ)
Q1. What is a for loop in Java?
A control statement that repeats a block of code while a condition is true, with the loop variable's initialization, condition and update written together in the header.
Q2. What are the three parts of a for loop?
Initialization (runs once), condition (checked before each iteration) and update (runs after each iteration), separated by semicolons.
Q3. When should I use a for loop instead of a while loop?
Use for when you count or know the number of iterations, such as looping over array indexes. Use while when you repeat until something happens and do not know in advance how many times.
Q4. How do I write an infinite for loop?
for (;;) { ... }. Leave out all three parts and end the loop with break or return when needed.
Q5. Can I declare multiple variables in a for loop?
Yes, if they have the same type: for (int i = 0, j = 10; i < j; i++, j--).
Q6. Can the loop variable be used after the loop?
Not if it is declared in the loop header; its scope ends with the loop. Declare it before the loop to use it afterwards.
Q7. What is a nested for loop?
A for loop inside another. The inner loop runs completely for each iteration of the outer loop, which is useful for matrices, tables and patterns.
Q8. Why does my loop throw ArrayIndexOutOfBoundsException?
The loop probably runs one step too far, for example i <= arr.length. The last valid index is arr.length - 1, so use i < arr.length.
Q9. Why does my for loop run only once?
Check for a semicolon right after the header: for (...);. It makes the loop body empty, so the block below runs only once after the loop finishes.
Q10. Can a for loop count backwards?
Yes: for (int i = 10; i >= 1; i--). Make sure the condition and update move toward each other so the loop ends.
Q11. Can I skip numbers in a for loop?
Yes, change the update: i += 2 for every second number, or use continue to skip specific iterations.
Q12. What is the difference between for and for-each?
A for loop uses an index and gives full control over the range and order. A for-each loop visits every element of an array or collection without an index and is simpler and safer for reading.
Q13. How do I exit a nested loop completely?
Use a labeled break: put a label before the outer loop (outer: for (...)) and write break outer; inside the inner loop. Alternatively, move the loops into a method and use return.
Q14. Is the condition checked before the first iteration?
Yes. If it is false at the start, the body never runs. Use a do-while loop if the body must run at least once.
Q15. Can I use a double as a loop counter?
You can, but rounding errors may make the loop run one time more or fewer than expected. Count with an int and calculate the decimal value from it.
Q16. What is the time complexity of nested loops?
For two loops of n iterations each, the body runs n² times, written O(n²). Large nested loops can become slow, so look for better algorithms when data grows.
Q17. Can I modify a list while looping over it with a for loop?
Removing elements by index shifts later elements and can skip some. Loop backwards when removing, or use removeIf() or an iterator.
Q18. What happens if the update part is missing?
The loop variable never changes unless the body changes it, so the loop may run forever. Missing parts are allowed, but make sure the loop can still end.
Q19. Is there an alternative to for loops in modern Java?
Yes. IntStream.range(0, n) and the Stream API can replace many loops, for example IntStream.rangeClosed(1, 100).sum(). Plain loops are still often the clearest choice.
Q20. Does a for loop body need braces?
Not for a single statement, but always using braces prevents bugs when more statements are added later.