Java Tutorial Series: This lesson is part of our comprehensive Complete Java Tutorial: Learn Java from Beginner to Advanced.
For Loop in Java: Syntax, Examples, Nested Loops and Best Practices
What Is a for Loop?
A for loop repeats a block of code while managing initialization, a continuation condition and an update expression. It is particularly useful when an iteration pattern is known or naturally expressed with a counter.
Basic Syntax
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Execution Order
The initialization runs once. Java checks the condition. If it is true, the body runs. The update then executes and the condition is checked again. This sequence continues until the condition becomes false.
Counting Up and Down
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
The update expression determines how the counter changes.
Looping Through Arrays
int[] scores = {80, 72, 91};
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Using length instead of a hard-coded bound prevents many indexing errors.
Enhanced for Loop
for (int score : scores) {
System.out.println(score);
}
Enhanced for is convenient when you need each element but do not need its index.
Nested for Loops
A loop can contain another loop. Nested loops are useful for matrices, tables and combinations.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.println(row + "," + col);
}
}
break and continue
break exits the loop early. continue skips the remainder of the current iteration. Both are useful when applied to clear conditions.
Infinite for Loops
for (;;) {
// repeats indefinitely
}
An infinite loop may be intentional in certain long-running processes, but it should have a safe termination strategy when the application requires one.
Off-by-One Errors
One of the most common loop bugs is executing once too many or too few times. Compare < with <= carefully and test the first and final expected values.
Performance and Complexity
A single loop over n elements is commonly O(n). A nested loop may be O(n²) depending on how its bounds relate to the input. Understanding iteration counts is important for algorithms and large datasets.
Practical Example: Sum
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
Practical Example: Find Maximum
int[] values = {12, 8, 31, 19};
int max = values[0];
for (int value : values) {
if (value > max) {
max = value;
}
}
Common Mistakes
Typical problems include wrong array bounds, forgetting the update, modifying the wrong variable, changing a collection during traversal incorrectly and putting expensive repeated work inside the loop.
Best Practices
Use meaningful counter names, keep loop bodies focused, use enhanced for when indexes are unnecessary, avoid repeated calculations that can be moved outside the loop and verify boundaries.
Practice Problems
Print 1–100, calculate factorial, count even numbers, find maximum/minimum, reverse an array, calculate an average and create a multiplication table.
Frequently Asked Questions
When should I use for? When the iteration structure naturally has initialization, condition and update.
What is enhanced for? A convenient traversal form for arrays and iterable data.
What is an off-by-one error? A boundary error causing an extra or missing iteration.
Conclusion
The for loop is central to Java programming and algorithmic thinking. Practice counters, arrays, nested loops, filtering and boundary testing before moving to while and do-while.
Learn More
- Java Syntax
- Java Variables
- Java Data Types
- Java Operators
- Java Input and Output
- Java Methods
- Java Arrays and Collections
Continue Learning Java
After this topic, continue through the Java control-flow path by practicing the next related statement or loop. Build small programs rather than only reading examples.
Deeper Practical Coverage
Loop Initialization, Condition and Update
The classic for loop places three control parts in one header. Initialization runs once, the condition is checked before each iteration, and the update runs after the body.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Execution is: initialize i → check condition → execute body → update i → check condition again.
Understanding this sequence prevents many beginner mistakes.
For Loop with Arrays
Array traversal is one of the most common uses of a for loop. Because arrays use zero-based indexes, the standard boundary is i < array.length.
int[] marks = {72, 81, 65, 90};
for (int i = 0; i < marks.length; i++) {
System.out.println("Index " + i + ": " + marks[i]);
}
Using i <= marks.length would eventually access an invalid index.
Enhanced For Loop and Collections
The enhanced for loop also works with Iterable collections.
List<String> names = List.of("Aman", "Riya", "Kabir");
for (String name : names) {
System.out.println(name);
}
It is concise when the program only needs each element. If you need the index, use an indexed loop or another suitable approach.
Nested Loops and Complexity
If an outer loop runs n times and an inner loop runs n times for each outer iteration, the total work can be O(n²). But not every nested loop is automatically O(n²). The actual bounds and relationship between the loops determine the complexity.
Always ask: how many times can the body execute?
Loop Invariants and Correctness
For algorithmic problems, it can help to identify what remains true after each iteration. For a running maximum, the invariant can be that max contains the largest value seen so far. Thinking this way makes loop-based algorithms easier to prove correct.
Large Data Sets
For large inputs, avoid unnecessary operations inside loops. Repeated string concatenation, expensive method calls, nested scans, and unnecessary object creation can become costly. First choose an appropriate algorithm and data structure; then optimize only where evidence shows a bottleneck.
Interview Perspective
Be prepared to explain the difference between for and enhanced for, identify off-by-one errors, calculate basic loop complexity, and trace nested loops. Practice predicting output without executing the program.
Extended Practice Set
- Traverse an array and calculate a sum.
- Find maximum and minimum.
- Search and stop at the first match.
- Print a triangular pattern.
- Analyze a nested loop's complexity.
Java Language and Version Note
The Java platform documentation groups control flow into decision-making, looping, and branching constructs. Modern Java has also expanded switch with expression forms, arrow rules, and pattern-oriented capabilities. When publishing this article, the website should state the Java version when an example depends on a newer language feature. Core syntax such as if, if-else, for, while, do-while, break, continue, and traditional switch remains foundational, while newer forms should be presented as version-aware additions.