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).

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

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

You COULD use a for-loop or a while-loop, but unless you specifically need the index of each object, you can use a for-each loop. Their syntaxes are much simpler, and they look much nicer

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

Here's the syntax:

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

You might be wondering why I'm putting "Object" here as the type. This is because as long as the collection stores two items in an array of some sort, this loop can work on it.

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