When you know exactly how many times you want to loop through a block of code, the for loop is your best tool. It is more concise than a while loop because it manages initialization, condition, and increment in a single line.
for loop is the industry standard for iterating over arrays and collections where the size is known beforehand.
A for loop consists of three main parts separated by semicolons:
The flow starts with initialization, then checks the condition. If true, it runs the code, updates the variable, and checks the condition again.
Java also offers an enhanced version of the for loop specifically for collections and arrays:
Gives you full control over the index. Best when you need to skip elements or change values at specific positions.
Used exclusively to loop through elements in an array. It is more readable and reduces the chance of "Off-by-one" errors.
A loop inside another loop. Commonly used for processing 2D arrays or matrices.
You can customize how the loop progresses by changing the third statement:
i++ or i += 2 to move forward.i-- to loop backwards (useful for reverse sorting).for(;;) creates a loop that never stops unless a break is called.| Feature | For Loop | For-Each Loop |
|---|---|---|
| Index Access | Available (via i) |
Not available |
| Syntax Complexity | Higher (3 parts) | Lower (Simplified) |
| Primary Use | General purpose logic | Arrays and Collections only |
The for loop is the workhorse of Java programming. Whether you are iterating over simple lists or complex data structures, mastering this loop is essential for writing clean, performant code.