Back to Study Material Java

For Loop in Java

The for loop is the most commonly used loop in Java because it conveniently keeps all three parts of loop control — initialization, condition, and update...

For Loop in Java

Precise Iteration Control with the For Loop

The for loop is the most commonly used loop in Java because it conveniently keeps all three parts of loop control — initialization, condition, and update — in a single line, making the loop's behavior immediately clear to a reader. It is particularly suited to iterating a known number of times or traversing an array using its index.

The syntax is: for (initialization; condition; update) { body }. The initialization runs once before the loop begins. The condition is checked before each iteration; if false from the start, the body never executes. The update runs at the end of each iteration, after the body. A standard counting loop from 0 to 9 looks like: for (int i = 0; i < 10; i++) { System.out.println(i); }.

You can declare multiple variables in the initialization section and include multiple expressions in the update section, separating them with commas: for (int i = 0, j = 10; i < j; i++, j--) { ... }. However, all variables in the initialization must be of the same type.

Any or all of the three sections can be empty. for (;;) { } is an infinite loop equivalent to while (true) { }. An empty condition section is treated as always-true. Empty initialization and update sections simply mean those steps are handled elsewhere.

The enhanced for loop (for-each) is syntactic sugar for iterating over arrays and any class that implements Iterable: for (String name : nameArray) { System.out.println(name); }. This form is cleaner and less error-prone than index-based loops when you do not need the index. However, it does not allow modifying the array itself (setting elements), does not provide direct access to the current index, and cannot iterate in reverse.

When you need index access while iterating a list, the traditional indexed for loop is appropriate: for (int i = 0; i < list.size(); i++) { System.out.println(i + ": " + list.get(i)); }. For ArrayList, get(i) is O(1); for LinkedList it is O(n), making the total loop O(n squared) — a performance trap to avoid with LinkedList.

A practical example of a for loop computing a factorial: int result = 1; for (int i = 1; i <= n; i++) { result *= i; }. After the loop, result holds n!.

Interview tip: Common for-loop interview questions include finding the sum of elements in an array, reversing an array in place, and searching for a value. Practice writing these with correct boundary conditions — off-by-one errors (using <= where < is correct, or starting at 1 instead of 0) are the most frequent mistake.