Multiple Variables in for Loop Initialization and Update
You'll learn: How to declare and manage multiple loop variables within a single for loop using comma-separated expressions.
The Core Idea
Sometimes you need to track more than one variable as your loop progresses. Java's for loop allows you to initialize multiple variables in the first section and update multiple variables in the third section by separating them with commas. This keeps related variables together in one compact loop structure.
Think of it like conducting an orchestra where two musicians play simultaneously—one moving forward through their sheet music while another moves backward through theirs, both coordinated by the same beat.
How It Works
In the initialization section, you can declare multiple variables of the same type using commas:
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i + ", j = " + j);
}
This loop starts with i at 0 and j at 10. After each iteration, i increments and j decrements. The loop continues while i is less than j.
Important: All variables in the initialization must share the same type. You cannot mix int i = 0, double d = 5.5 in one declaration.
You can also use multiple already-declared variables of different types:
int i;
double d;
for (i = 0, d = 10.0; i < 5; i++, d -= 0.5) {
System.out.println("i = " + i + ", d = " + d);
}
Common Use Cases
- Traversing arrays or ranges from both ends simultaneously
- Maintaining a counter alongside another changing value
- Coordinating related calculations that evolve together
Key Takeaway: Use comma-separated expressions in for loop initialization and update sections to manage multiple variables that change together, keeping your loop logic clear and coordinated.