0
0
Javaprogramming~10 mins

Enhanced for loop in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Enhanced for loop
Start with array or collection
Pick next element
Execute loop body with element
More elements?
NoExit loop
Back to Pick next element
The enhanced for loop goes through each item in a collection or array one by one, running the loop body for each item until all are done.
Execution Sample
Java
int[] nums = {1, 2, 3};
for (int num : nums) {
    System.out.println(num);
}
Prints each number in the array nums one by one using an enhanced for loop.
Execution Table
Iterationnum valueActionOutput
11Print num1
22Print num2
33Print num3
--No more elements, exit loop-
💡 All elements in nums array have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
num-123-
Key Moments - 2 Insights
Why don't we need to use an index variable like in a normal for loop?
The enhanced for loop automatically picks each element in order, so you don't need to manage an index yourself. See execution_table rows 1-3 where num takes each value directly.
Can we modify the array elements using the enhanced for loop variable?
No, the loop variable 'num' is a copy of each element's value, so changing it won't affect the original array. This is shown because 'num' changes but the array stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' at iteration 2?
A1
B2
C3
DNone
💡 Hint
Check the 'num value' column in the execution_table at iteration 2.
At which iteration does the enhanced for loop stop running?
AAfter iteration 3
BAfter iteration 2
CAfter iteration 1
DNever stops
💡 Hint
Look at the exit_note and the last iteration row in the execution_table.
If the array nums was empty, what would happen to the loop execution?
ALoop runs once with num = 0
BLoop runs infinitely
CLoop does not run at all
DError occurs
💡 Hint
Enhanced for loop runs zero times if there are no elements to process, see concept_flow for loop start.
Concept Snapshot
Enhanced for loop syntax:
for (Type var : collection) {
    // use var
}

It automatically loops over each element.
No index needed.
Loop ends after last element.
Full Transcript
The enhanced for loop in Java lets you go through each item in an array or collection easily. You write for (Type var : collection) and inside the loop, var holds the current item. The loop runs once for each element. You don't need to use an index or worry about the length. When all elements are done, the loop stops. For example, if nums is {1, 2, 3}, the loop runs three times with num = 1, then 2, then 3, printing each number. This is simpler and less error-prone than a normal for loop with an index.