In Part 1, we learned about the while loop, which is ideal when the number of iterations is unknown.
In Part 2, we explored the do-while loop, which guarantees that the loop body executes at least once.
Now it's time to learn the most commonly used loop in Java—the for loop.
If you've written Java code before, chances are you've used a for loop. It's concise, flexible, and perfect when you know how many times you want to repeat an operation.
In this article, we'll cover everything from basic syntax to advanced interview questions and common compiler rules.
What Is the for Loop?
A for loop repeatedly executes a block of code until a specified condition becomes false.
It is best suited for situations where the number of iterations is known in advance.
Common examples include:
- Printing numbers
- Traversing arrays
- Processing lists
- Nested loops
- Matrix operations
- Algorithm implementation
Syntax
for (initialization; condition; update) {
// loop body
}
The for loop has three sections:
- Initialization – Executes once before the loop starts.
- Condition – Checked before every iteration.
- Update – Executes after each iteration.
How the for Loop Works
Execution order:
- Initialization
- Condition
- Loop body
- Update
- Repeat from step 2
If the condition becomes false, the loop terminates.
Your First for Loop
for (int count = 1; count <= 5; count++) {
System.out.println(count);
}
Output
1
2
3
4
5
Printing Even Numbers
for (int number = 2; number <= 10; number += 2) {
System.out.println(number);
}
Output
2
4
6
8
10
Understanding Each Section
1. Initialization
The initialization section executes only once.
for (int count = 1; count <= 3; count++) {
System.out.println(count);
}
Here,
int count = 1;
runs only once before the loop begins.
2. Condition
The condition must evaluate to a boolean.
for (int count = 1; count <= 3; count++) {
System.out.println(count);
}
When
count <= 3
becomes false, the loop stops.
3. Update
The update section executes after every iteration.
count++;
The update section can contain almost any valid Java statement.
All Three Sections Are Optional
One of the most interesting facts about the for loop is that all three sections are optional.
The following is perfectly valid:
for (;;) {
System.out.println("Running...");
}
This is an infinite loop.
The compiler treats the missing condition as
true
Infinite for Loop
for (;;) {
System.out.println("Infinite Loop");
}
Output
Infinite Loop
Infinite Loop
Infinite Loop
...
Multiple Variables
The initialization section can declare multiple variables.
for (int left = 1, right = 5; left <= right; left++, right--) {
System.out.println(left + " " + right);
}
Output
1 5
2 4
3 3
Variables Must Be the Same Type
Correct
for (int x = 1, y = 10; x < y; x++, y--) {
}
Incorrect
for (int x = 1, boolean finished = false; x < 5; x++) {
}
Compile-time error
Variables declared together must have the same type.
Method Calls in the Initialization Section
The initialization section isn't limited to variable declarations.
You can execute any valid Java statement.
int count = 1;
for (System.out.println("Starting Loop"); count <= 3; count++) {
System.out.println(count);
}
Output
Starting Loop
1
2
3
The initialization statement executes only once.
Method Calls in the Update Section
The update section can also execute method calls.
int count = 1;
for (; count <= 3; System.out.println("Next Iteration")) {
count++;
}
Output
Next Iteration
Next Iteration
Next Iteration
Omitting the Initialization
Initialization is optional.
int count = 1;
for (; count <= 3; count++) {
System.out.println(count);
}
Omitting the Update
The update can be moved into the loop body.
for (int count = 1; count <= 3;) {
System.out.println(count);
count++;
}
Omitting the Condition
for (int count = 1;; count++) {
System.out.println(count);
}
This is another infinite loop.
Unreachable Statement Rule
Java reports an error whenever it knows that some code can never execute.
Case 1
for (int i = 0; true; i++) {
}
System.out.println("Done");
Compile-time error
unreachable statement
The compiler knows the loop never exits.
Case 2
for (int i = 0; false; i++) {
System.out.println(i);
}
Compile-time error
unreachable statement
The loop body can never execute.
Case 3
int start = 10;
int end = 20;
for (int i = 0; start < end; i++) {
}
System.out.println("Done");
This compiles successfully.
The compiler cannot determine the values of start and end during compilation.
Effect of final
final int start = 10;
final int end = 20;
for (int i = 0; start < end; i++) {
}
System.out.println("Done");
Compile-time error
unreachable statement
The compiler replaces
start < end
with
10 < 20
which becomes
true
The loop is now known to be infinite.
Nested for Loops
Nested loops are commonly used for matrices and patterns.
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
System.out.print("* ");
}
System.out.println();
}
Output
* * *
* * *
* * *
Execution Trace
for (int count = 1; count <= 3; count++) {
System.out.println(count);
}
| Iteration | count before | Condition | Output | count after |
|---|---|---|---|---|
| 1 | 1 | true | 1 | 2 |
| 2 | 2 | true | 2 | 3 |
| 3 | 3 | true | 3 | 4 |
| 4 | 4 | false | — | — |
Common Beginner Mistakes
Forgetting the Update
for (int count = 1; count <= 5;) {
System.out.println(count);
}
Result
Infinite loop.
Using Assignment Instead of Comparison
boolean running = false;
for (; running = true;) {
}
The assignment returns true, causing an infinite loop.
Using Different Variable Types
Incorrect
for (int x = 1, boolean done = false; x < 5; x++) {
}
Variables declared together must have the same type.
Forgetting That All Sections Are Optional
Many beginners believe all three sections are mandatory.
In reality,
for (;;) {
}
is completely valid.
Best Practices
- Use a
forloop when the number of iterations is known. - Keep the initialization, condition, and update simple.
- Prefer meaningful variable names like
index,row,column, orcount. - Avoid modifying the loop variable inside the body unless necessary.
- Use braces even for single statements.
- Keep nested loops readable by using descriptive variable names.
Interview Questions
Which loop is most commonly used in Java?
The for loop.
Are all three sections mandatory?
No.
Initialization, condition, and update are all optional.
What happens if the condition is omitted?
The compiler treats it as
true
creating an infinite loop.
Can method calls appear in the initialization or update section?
Yes.
Both sections can contain valid Java statements.
Why can adding final produce an unreachable statement error?
Because final variables initialized with constants become compile-time constants, allowing the compiler to determine that the loop is infinite.
while vs for
| Feature | while |
for |
|---|---|---|
| Best for | Unknown iterations | Known iterations |
| Initialization | Outside loop | Inside loop |
| Update | Manual | Built into syntax |
| Readability | Good | Excellent for counting loops |
Quick Memory Trick 🧠
Remember FOR:
- F → Fixed number of iterations
- O → Optional sections
- R → Repeats until the condition becomes false
Or simply remember:
"Know the count? Use
for."
Key Takeaways
- The
forloop is ideal when the number of iterations is known. - It consists of initialization, condition, and update sections.
- All three sections are optional.
- Omitting the condition creates an infinite loop.
- Multiple variables can be declared if they share the same type.
- Method calls are allowed in the initialization and update sections.
-
finalvariables can affect compile-time unreachable statement analysis. - Nested
forloops are commonly used for patterns, matrices, and algorithms.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)