How does the for each statement work?

I’m not sure if this is in the right topic but im trying to get my head around on how the for each statement works over the original for statement?

Im following one of Mosh’s data structure courses, the section which involves Arrays, and im trying to figure out how this line of the for each statement can be converted to a original for statement to find the max value of an element inside the array?

Code:

public int max() {
    int max = 0;

    for (int item : items) {
        if (item > max) {
            max = item;
        }
    }
    return max;
}

It is just a shorter/prettier way of doing a normal for loop. Keep in mind that if you need access to the current index value of the array you are iterating through, this shortened form does not give you that ability.

In your example, the code would look like this:

for (int i = 0; i < items.length; i++)
    if (items[i] > max) {
        max = items[i];
    }
1 Like