For-Each Loops

For-Each loops are different from the other loops I mentioned in Loops, as they are specifically designed for traversing an array (accessing every element in an array).

Let's say this was an array that you wanted to traverse through.

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};

If you had a for-each loop that you wanted to use to traverse this away, it'll access each element left to right. For example, if I were to use a for-each loop and

for (int num : arr) {
   System.out.println(i + ", "); /* output: 1, 2, 3, 4, 5, 6, 7, 8, */
   
}

Here's its syntax:

for (Object item : Object[] collection) {
    [code]
}

Item

This is the current item that the for-each loop is on. However, you can only access its valueβ€” you can't change it or anything.

Collection

This is just the collection that the for-each loop is traversing through. The collection can be basically anything that can hold more than one value.

If you are using a for-each loop on a collection, do NOT modify it as you're traversing through the collection or you'll have a fun time dealing with logic errors.

Last updated