Java For Loop
A Java for loop repeatedly executes a block of statements while a condition remains true. It is commonly used when the number of iterations is known in advance, such as counting through a range, visiting array indexes, or repeating an operation a fixed number of times.
The standard for loop keeps initialization, condition checking, and variable updates in one statement. Java also provides the enhanced for loop for reading elements from arrays and other iterable collections.
Java For Loop Syntax
The syntax of a Java for loop is:
for(initialization; condition; update) {
//statements
}
- initialization runs once before the loop starts. It usually declares and initializes a loop-control variable.
- condition is evaluated before every iteration. The loop body runs only when this expression evaluates to
true. - update runs after each completed iteration. It commonly increments or decrements the loop-control variable.
- statements are the instructions repeated during each iteration.
The three control sections are separated by semicolons. Any section may be omitted, but both semicolons must remain.
How a Java For Loop Executes
The following flowchart shows the execution order of a Java for loop.
- Java executes the
initializationsection once. - Java evaluates the
condition. - If the condition is
true, Java executes the loop body. - Java executes the
updatesection. - Control returns to the condition check.
- When the condition becomes
false, execution continues with the statement after the loop.
Because the condition is checked before the body, a Java for loop may execute zero times.
Java For Loop Example: Print Numbers from 0 to 4
In this example, i starts at 0. The loop runs while i < 5, and i++ increases its value by one after each iteration.
Example.java
public class Example {
public static void main(String[] args) {
for(int i=0;i<5;i++) {
System.out.println(i);
}
}
}
When you run the program, it prints:
Output
0
1
2
3
4
The value 5 is not printed because the condition uses the less-than operator. When i becomes 5, i < 5 is false.
Java For Loop for Array Indexes
Use an index-based for loop when you need the position of each array element. Valid array indexes start at 0 and end at array.length - 1, so the loop condition should normally use i < array.length.
Example.java
public class Example {
public static void main(String[] args) {
String[] names = {"Apple", "Google", "Apache"};
for(int i=0;i<names.length;i++) {
System.out.println(names[i]);
}
}
}
When you run the program, all array elements are printed in index order.
Output
Apple
Google
Apache
Java Enhanced For Loop for Array Elements
The enhanced for loop, also called the for-each loop, reads each element directly. It avoids manual index initialization, boundary checks, and increments.
Example.java
public class Example {
public static void main(String[] args) {
String[] names = {"Apple", "Google", "Apache"};
for(String name: names) {
System.out.println(name);
}
}
}
When you run the program, it prints:
Output
Apple
Google
Apache
Use the enhanced loop when you only need each value. Use the standard loop when you need an index, want to move backward, need a custom step size, or must update elements by position.
Java For Loop That Counts Backward
A for loop can decrement its control variable. The following loop prints numbers from 5 down to 1.
public class Example {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
}
}
Output
5
4
3
2
1
Java For Loop with a Custom Step
The update section is not limited to i++. This example increases i</code by <code>2 and prints the even numbers from 0 through 10.
public class Example {
public static void main(String[] args) {
for (int i = 0; i <= 10; i += 2) {
System.out.println(i);
}
}
}
Output
0
2
4
6
8
10
Java Infinite For Loop
The condition section is optional. If no terminating condition is present, the loop continues until the program is stopped, an exception occurs, or a statement such as break exits the loop.
Example.java
public class Example {
public static void main(String[] args) {
for(int i=0; ;i++) {
System.out.println(i);
}
}
}
This program prints increasing integers indefinitely. Infinite loops are appropriate only when the application intentionally runs continuously and includes a controlled way to stop or exit.
A compact infinite-loop form is for (;;) { ... }. Both semicolons are required even though all three control expressions are omitted.
Java Nested For Loop for a Star Pattern
A nested for loop places one loop inside another. For each iteration of the outer loop, the inner loop completes all of its iterations.
The following program prints a five-row star pattern. The outer loop controls the row number, and the inner loop prints the stars in that row.
Example.java
public class JavaTutorial {
public static void main(String[] args) {
for(int i=1;i<6;i++) {
for(int j=0;j<i;j++) {
System.out.print("*");
}
System.out.println();
}
}
}
When you run the program, it prints:
Output
*
**
***
****
*****
Exit a Java For Loop with Break
A loop normally ends when its condition becomes false. The break statement ends the nearest enclosing loop immediately and transfers control to the next statement after that loop.
In this example, the loop stops when i becomes 4.
Example.java
public class Example {
public static void main(String[] args) {
for(int i=1;i<10;i++) {
if(i==4) {
break;
}
System.out.println(i);
}
}
}
When you run the program, it prints:
Output
1
2
3
Skip a Java For Loop Iteration with Continue
The continue statement skips the remaining statements in the current iteration. Java then executes the update section and checks the condition for the next iteration.
In this example, the value 4 is skipped.
Example.java
public class Example {
public static void main(String[] args) {
for(int i=1;i<8;i++) {
if(i==4) {
continue;
}
System.out.println(i);
}
}
}
When you run the program, it prints:
Output
1
2
3
5
6
7
Multiple Variables in a Java For Loop
The initialization and update sections may contain multiple expressions separated by commas. Variables declared together must have compatible types.
public class Example {
public static void main(String[] args) {
for (int left = 0, right = 4; left < right; left++, right--) {
System.out.println(left + " " + right);
}
}
}
Output
0 4
1 3
Variable Scope in a Java For Loop
A variable declared in the initialization section is scoped to the loop. It can be used in the condition, update section, and loop body, but it is not available after the loop ends.
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
// System.out.println(i); // Compile-time error: i is out of scope
Declare the variable before the loop when its final value is needed afterward.
Common Java For Loop Errors
- Off-by-one condition: use
i < array.length, noti <= array.length, when accessing array indexes. - Update moves in the wrong direction: a loop with
i > 0must normally decrementi, not increment it. - Condition never changes: verify that the loop body or update section eventually makes the condition
false. - Accidental semicolon:
for (...);creates an empty loop body, so the following block is not controlled by the loop. - Changing a collection structurally during iteration: use an appropriate iterator or collection operation instead of modifying it unsafely inside an enhanced loop.
Java For Loop and While Loop Comparison
| Requirement | Suitable loop |
|---|---|
| Known counter, range, or step | Standard for loop |
| Read every array or iterable element without an index | Enhanced for loop |
| Repeat until a condition changes at an unpredictable time | while loop |
| Execute the body at least once before checking the condition | do-while loop |
Java For Loop FAQs
Can a Java for loop run zero times?
Yes. Java checks the condition before the first iteration. If it is initially false, the loop body does not execute.
Can all three sections of a Java for loop be omitted?
Yes. for (;;) { ... } is valid and creates an infinite loop. The two semicolons are still required.
What is the difference between break and continue in a Java for loop?
break ends the loop completely. continue skips the rest of the current iteration and proceeds with the next iteration.
When should I use the enhanced for loop in Java?
Use it when you need to read each element of an array or iterable and do not need the element’s index, a reverse order, or a custom step.
Java For Loop Editorial QA Checklist
- Confirm that every index-based array example uses a boundary below
array.length. - Check that each update expression moves the loop variable toward a false condition.
- Verify that output blocks match the exact iteration range and order.
- Distinguish standard, enhanced, nested, infinite,
break, andcontinuebehavior accurately. - Compile new examples with a current Java compiler before publication.
Java For Loop Summary
A Java for loop is well suited to counter-controlled repetition. Its initialization runs once, its condition is checked before each iteration, and its update runs after each completed iteration. Use an index-based loop when position matters, an enhanced loop when only element values are needed, and break or continue when control must change inside the loop. Continue with the main Java Tutorial for related control-flow topics.
TutorialKart.com