The for loop is used to repeat a block of code a specific number of times. It is particularly useful when you know the exact number of iterations beforehand. A for loop includes initialization, a termination condition, and an update statement all in one line, making it a concise choice for counting loops.
for Loopfor (initialization; condition; update) {
// Code to execute
}
true, the loop continues; if false, the loop stops.for Loopfor (int i = 0; i < 5; i++) {
System.out.println("Count is: " + i);
}
In this example, i starts at 0 and increments by 1 after each iteration. The loop continues while i < 5, so it prints numbers from 0 to 4.
for Loopfor Loop (For-Each Loop) – Iterating Over Arrays and CollectionsThe Enhanced for loop, or For-Each loop, is designed for iterating through elements in an array or any Collection (like lists, sets, etc.) without using an explicit counter. It provides a clean and readable way to access each element directly, particularly when you don’t need to modify the index or control variable.
for Loopfor (elementType element : collection) {
// Code to execute with element
}
elementType: The data type of elements in the collection or array.element: A temporary variable representing each element in the array or collection during the iteration.collection: The array or Collection to iterate through.for Loop with an Arrayint[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number is: " + num);
}
In this example, each element in the numbers array is stored in num as the loop iterates, printing each number from 1 to 5.
for Loopfor Loop and Enhanced for Loop| Feature | for Loop | Enhanced for Loop |
|---|---|---|
| Structure | Initialization, condition, update all in one line | Uses element : collection syntax for readability |
| Best for | Known number of iterations, index-based operations | Iterating through each element in arrays or collections |
| Control | Full control over index variable | Direct access to elements only, no index |
| Modifications | Can modify the index or elements | Not suited for modifying or skipping elements directly |