The for loop is a counter-controlled iteration statement widely favored when the exact number of execution repetitions is known prior to loop entry.
// For Loop Syntax:
for (initialization; boolean_condition; update_step) {
// Loop body statements
}
int i = 1).boolean_condition. If true, proceeds to body. If false, loop terminates immediately.i++).Nested for loops (a loop residing inside an outer loop) are a staple in university practical exams for generating coordinate grids and geometric shapes:
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
// Outer loop controls number of rows
for (int i = 1; i <= rows; i++) {
// Inner loop 1: Prints leading spaces for centering
for (int space = 1; space <= rows - i; space++) {
System.out.print(" ");
}
// Inner loop 2: Prints asterisks
for (int star = 1; star <= (2 * i - 1); star++) {
System.out.print("*");
}
// Move to next line
System.out.println();
}
}
}
*
***
*****
*******
*********
Exam Tracing Problem: "Can multiple variables be initialized and updated in a single for loop header?"
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}
Answer: Yes! Java permits multiple variables of the same type separated by commas in the initialization section, and multiple update statements separated by commas in the step section.
Now let us explore the cleaner Enhanced For-Each Loop for traversing arrays and collections. Proceed to: Java For-Each Loop →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Cleaner iteration over arrays and collections.
Interrupting loop cycles.
Iterating array elements.
Nested loop pattern challenges.