for Loop
The for loop is one of the most fundamental building blocks in Java programming.
It is designed for situations where you know in advance exactly how many times you want to repeat a block of code.
The power of the for loop comes from its compact structure, which combines three key parts โ the initialization, the condition, and the update expression โ into a single line.
When the program reaches a for loop, it first sets up a starting value (like int i = 0
), checks whether the condition is true (for example i < 5
), and then runs the loop body.
After each run, the update expression (like i++
) changes the counter, and the condition is checked again.
If the condition is still true, the loop continues; if not, the loop stops.
In the real world, for loops are used everywhere in web applications.
You use them to loop through an array of user records, generate table rows dynamically, paginate results, process multiple form inputs, or repeat an action a fixed number of times โ like sending a notification email to every user in a list.
Good for loops are predictable and clear:
Always make sure the loop condition will eventually become false, or you risk creating an infinite loop that crashes the program.
Keep loop counters (i
, j
, etc.) clear and meaningful when needed.
Avoid deeply nested for loops if possible โ they can be hard to read and slow down performance.
In modern Java development, for loops are also combined with break and continue to control the flow, making them flexible enough to handle exceptions or special cases inside the loop.
Once you fully understand the for loopโs flow โ start โ condition โ body โ update โ repeat โ you can design any repeatable logic with confidence.
Mini Lab
A nested for loop is simply putting one for loop inside another.
This is how you handle situations where you have two or more levels of repetition.
A classic example is a table โ you repeat rows, and inside each row, you repeat columns.
When a nested for loop runs, the outer loop controls the main level (like rows), and the inner loop handles the secondary level (like cells or columns).
For every single iteration of the outer loop, the inner loop runs fully from start to finish.
In web development, nested loops appear when you generate grid layouts, build calendars, loop over combinations of items (like all possible product pairs), or handle matrix-style data from CSV files or spreadsheets.
However, nested loops can multiply the total work your program does very quickly.
If the outer loop runs 100 times and the inner loop runs 100 times, thatโs 10,000 iterations total.
So itโs critical to check whether you really need both loops, or if thereโs a better algorithm or data structure.
Best practices for nested for loops:
Use clear variable names (row
, col
, i
, j
are common).
Avoid using the same counter name in both loops.
Keep the loop body small and efficient โ heavy work inside nested loops can slow your app dramatically.
For complex operations, consider extracting the logic into helper methods.
Once you get comfortable with nested for loops, you unlock the ability to process any structured, multi-level data in a clean and repeatable way.
Mini Lab
The enhanced for loop, also called the for-each loop, is a modern, more readable way to iterate over collections and arrays.
Instead of manually setting a counter and using an index, the for-each loop automatically gives you each item in the collection one by one.
This makes your code shorter, cleaner, and safer, because it removes common mistakes like off-by-one errors or accidentally skipping elements.
For-each is perfect when:
You only need the value, not the index.
You donโt need to modify the collectionโs size during the loop.
You want to process all items without worrying about boundaries.
In real-world web projects, for-each is used to display a list of user comments, loop through orders in a cart, process uploaded files, or validate form fields.
Many Java web frameworks produce lists and arrays that you can process easily with a for-each loop.
However, for-each has some limitations:
You canโt remove or add items to the collection inside the loop (this causes a ConcurrentModificationException
).
If you need the index too, youโll need a regular for loop instead.
When you master for-each, you save time, reduce bugs, and write more readable code โ which is why itโs one of the most loved features of modern Java syntax.
Mini Lab